blob: 72b028cde61bcd4d6bb691371586a80baad9ba65 [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.org5a8ca6c2008-10-23 13:57:19 +000040 ASSERT((space).low() <= (info).top \
41 && (info).top <= (space).high() \
42 && (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;
136 default:
137 UNREACHABLE();
138 }
139}
140
141
142// -----------------------------------------------------------------------------
143// Page
144
145#ifdef DEBUG
146Page::RSetState Page::rset_state_ = Page::IN_USE;
147#endif
148
149// -----------------------------------------------------------------------------
150// MemoryAllocator
151//
152int MemoryAllocator::capacity_ = 0;
153int MemoryAllocator::size_ = 0;
154
155VirtualMemory* MemoryAllocator::initial_chunk_ = NULL;
156
157// 270 is an estimate based on the static default heap size of a pair of 256K
158// semispaces and a 64M old generation.
159const int kEstimatedNumberOfChunks = 270;
160List<MemoryAllocator::ChunkInfo> MemoryAllocator::chunks_(
161 kEstimatedNumberOfChunks);
162List<int> MemoryAllocator::free_chunk_ids_(kEstimatedNumberOfChunks);
163int MemoryAllocator::max_nof_chunks_ = 0;
164int MemoryAllocator::top_ = 0;
165
166
167void MemoryAllocator::Push(int free_chunk_id) {
168 ASSERT(max_nof_chunks_ > 0);
169 ASSERT(top_ < max_nof_chunks_);
170 free_chunk_ids_[top_++] = free_chunk_id;
171}
172
173
174int MemoryAllocator::Pop() {
175 ASSERT(top_ > 0);
176 return free_chunk_ids_[--top_];
177}
178
179
180bool MemoryAllocator::Setup(int capacity) {
181 capacity_ = RoundUp(capacity, Page::kPageSize);
182
183 // Over-estimate the size of chunks_ array. It assumes the expansion of old
184 // space is always in the unit of a chunk (kChunkSize) except the last
185 // expansion.
186 //
187 // Due to alignment, allocated space might be one page less than required
188 // number (kPagesPerChunk) of pages for old spaces.
189 //
kasper.lund7276f142008-07-30 08:49:36 +0000190 // Reserve two chunk ids for semispaces, one for map space, one for old
191 // space, and one for code space.
192 max_nof_chunks_ = (capacity_ / (kChunkSize - Page::kPageSize)) + 5;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000193 if (max_nof_chunks_ > kMaxNofChunks) return false;
194
195 size_ = 0;
196 ChunkInfo info; // uninitialized element.
197 for (int i = max_nof_chunks_ - 1; i >= 0; i--) {
198 chunks_.Add(info);
199 free_chunk_ids_.Add(i);
200 }
201 top_ = max_nof_chunks_;
202 return true;
203}
204
205
206void MemoryAllocator::TearDown() {
207 for (int i = 0; i < max_nof_chunks_; i++) {
208 if (chunks_[i].address() != NULL) DeleteChunk(i);
209 }
210 chunks_.Clear();
211 free_chunk_ids_.Clear();
212
213 if (initial_chunk_ != NULL) {
214 LOG(DeleteEvent("InitialChunk", initial_chunk_->address()));
215 delete initial_chunk_;
216 initial_chunk_ = NULL;
217 }
218
219 ASSERT(top_ == max_nof_chunks_); // all chunks are free
220 top_ = 0;
221 capacity_ = 0;
222 size_ = 0;
223 max_nof_chunks_ = 0;
224}
225
226
227void* MemoryAllocator::AllocateRawMemory(const size_t requested,
kasper.lund7276f142008-07-30 08:49:36 +0000228 size_t* allocated,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000229 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000230 if (size_ + static_cast<int>(requested) > capacity_) return NULL;
231
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000232 void* mem = OS::Allocate(requested, allocated, executable == EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000233 int alloced = *allocated;
234 size_ += alloced;
235 Counters::memory_allocated.Increment(alloced);
236 return mem;
237}
238
239
240void MemoryAllocator::FreeRawMemory(void* mem, size_t length) {
241 OS::Free(mem, length);
242 Counters::memory_allocated.Decrement(length);
243 size_ -= length;
244 ASSERT(size_ >= 0);
245}
246
247
248void* MemoryAllocator::ReserveInitialChunk(const size_t requested) {
249 ASSERT(initial_chunk_ == NULL);
250
251 initial_chunk_ = new VirtualMemory(requested);
252 CHECK(initial_chunk_ != NULL);
253 if (!initial_chunk_->IsReserved()) {
254 delete initial_chunk_;
255 initial_chunk_ = NULL;
256 return NULL;
257 }
258
259 // We are sure that we have mapped a block of requested addresses.
260 ASSERT(initial_chunk_->size() == requested);
261 LOG(NewEvent("InitialChunk", initial_chunk_->address(), requested));
262 size_ += requested;
263 return initial_chunk_->address();
264}
265
266
267static int PagesInChunk(Address start, size_t size) {
268 // The first page starts on the first page-aligned address from start onward
269 // and the last page ends on the last page-aligned address before
270 // start+size. Page::kPageSize is a power of two so we can divide by
271 // shifting.
272 return (RoundDown(start + size, Page::kPageSize)
273 - RoundUp(start, Page::kPageSize)) >> Page::kPageSizeBits;
274}
275
276
277Page* MemoryAllocator::AllocatePages(int requested_pages, int* allocated_pages,
278 PagedSpace* owner) {
279 if (requested_pages <= 0) return Page::FromAddress(NULL);
280 size_t chunk_size = requested_pages * Page::kPageSize;
281
282 // There is not enough space to guarantee the desired number pages can be
283 // allocated.
284 if (size_ + static_cast<int>(chunk_size) > capacity_) {
285 // Request as many pages as we can.
286 chunk_size = capacity_ - size_;
287 requested_pages = chunk_size >> Page::kPageSizeBits;
288
289 if (requested_pages <= 0) return Page::FromAddress(NULL);
290 }
kasper.lund7276f142008-07-30 08:49:36 +0000291 void* chunk = AllocateRawMemory(chunk_size, &chunk_size, owner->executable());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000292 if (chunk == NULL) return Page::FromAddress(NULL);
293 LOG(NewEvent("PagedChunk", chunk, chunk_size));
294
295 *allocated_pages = PagesInChunk(static_cast<Address>(chunk), chunk_size);
296 if (*allocated_pages == 0) {
297 FreeRawMemory(chunk, chunk_size);
298 LOG(DeleteEvent("PagedChunk", chunk));
299 return Page::FromAddress(NULL);
300 }
301
302 int chunk_id = Pop();
303 chunks_[chunk_id].init(static_cast<Address>(chunk), chunk_size, owner);
304
305 return InitializePagesInChunk(chunk_id, *allocated_pages, owner);
306}
307
308
309Page* MemoryAllocator::CommitPages(Address start, size_t size,
310 PagedSpace* owner, int* num_pages) {
311 ASSERT(start != NULL);
312 *num_pages = PagesInChunk(start, size);
313 ASSERT(*num_pages > 0);
314 ASSERT(initial_chunk_ != NULL);
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000315 ASSERT(InInitialChunk(start));
316 ASSERT(InInitialChunk(start + size - 1));
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000317 if (!initial_chunk_->Commit(start, size, owner->executable() == EXECUTABLE)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000318 return Page::FromAddress(NULL);
319 }
320 Counters::memory_allocated.Increment(size);
321
322 // So long as we correctly overestimated the number of chunks we should not
323 // run out of chunk ids.
324 CHECK(!OutOfChunkIds());
325 int chunk_id = Pop();
326 chunks_[chunk_id].init(start, size, owner);
327 return InitializePagesInChunk(chunk_id, *num_pages, owner);
328}
329
330
kasper.lund7276f142008-07-30 08:49:36 +0000331bool MemoryAllocator::CommitBlock(Address start,
332 size_t size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000333 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000334 ASSERT(start != NULL);
335 ASSERT(size > 0);
336 ASSERT(initial_chunk_ != NULL);
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000337 ASSERT(InInitialChunk(start));
338 ASSERT(InInitialChunk(start + size - 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000339
kasper.lund7276f142008-07-30 08:49:36 +0000340 if (!initial_chunk_->Commit(start, size, executable)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000341 Counters::memory_allocated.Increment(size);
342 return true;
343}
344
345
346Page* MemoryAllocator::InitializePagesInChunk(int chunk_id, int pages_in_chunk,
347 PagedSpace* owner) {
348 ASSERT(IsValidChunk(chunk_id));
349 ASSERT(pages_in_chunk > 0);
350
351 Address chunk_start = chunks_[chunk_id].address();
352
353 Address low = RoundUp(chunk_start, Page::kPageSize);
354
355#ifdef DEBUG
356 size_t chunk_size = chunks_[chunk_id].size();
357 Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
358 ASSERT(pages_in_chunk <=
359 ((OffsetFrom(high) - OffsetFrom(low)) / Page::kPageSize));
360#endif
361
362 Address page_addr = low;
363 for (int i = 0; i < pages_in_chunk; i++) {
364 Page* p = Page::FromAddress(page_addr);
365 p->opaque_header = OffsetFrom(page_addr + Page::kPageSize) | chunk_id;
366 p->is_normal_page = 1;
367 page_addr += Page::kPageSize;
368 }
369
370 // Set the next page of the last page to 0.
371 Page* last_page = Page::FromAddress(page_addr - Page::kPageSize);
372 last_page->opaque_header = OffsetFrom(0) | chunk_id;
373
374 return Page::FromAddress(low);
375}
376
377
378Page* MemoryAllocator::FreePages(Page* p) {
379 if (!p->is_valid()) return p;
380
381 // Find the first page in the same chunk as 'p'
382 Page* first_page = FindFirstPageInSameChunk(p);
383 Page* page_to_return = Page::FromAddress(NULL);
384
385 if (p != first_page) {
386 // Find the last page in the same chunk as 'prev'.
387 Page* last_page = FindLastPageInSameChunk(p);
388 first_page = GetNextPage(last_page); // first page in next chunk
389
390 // set the next_page of last_page to NULL
391 SetNextPage(last_page, Page::FromAddress(NULL));
392 page_to_return = p; // return 'p' when exiting
393 }
394
395 while (first_page->is_valid()) {
396 int chunk_id = GetChunkId(first_page);
397 ASSERT(IsValidChunk(chunk_id));
398
399 // Find the first page of the next chunk before deleting this chunk.
400 first_page = GetNextPage(FindLastPageInSameChunk(first_page));
401
402 // Free the current chunk.
403 DeleteChunk(chunk_id);
404 }
405
406 return page_to_return;
407}
408
409
410void MemoryAllocator::DeleteChunk(int chunk_id) {
411 ASSERT(IsValidChunk(chunk_id));
412
413 ChunkInfo& c = chunks_[chunk_id];
414
415 // We cannot free a chunk contained in the initial chunk because it was not
416 // allocated with AllocateRawMemory. Instead we uncommit the virtual
417 // memory.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000418 if (InInitialChunk(c.address())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000419 // TODO(1240712): VirtualMemory::Uncommit has a return value which
420 // is ignored here.
421 initial_chunk_->Uncommit(c.address(), c.size());
422 Counters::memory_allocated.Decrement(c.size());
423 } else {
424 LOG(DeleteEvent("PagedChunk", c.address()));
425 FreeRawMemory(c.address(), c.size());
426 }
427 c.init(NULL, 0, NULL);
428 Push(chunk_id);
429}
430
431
432Page* MemoryAllocator::FindFirstPageInSameChunk(Page* p) {
433 int chunk_id = GetChunkId(p);
434 ASSERT(IsValidChunk(chunk_id));
435
436 Address low = RoundUp(chunks_[chunk_id].address(), Page::kPageSize);
437 return Page::FromAddress(low);
438}
439
440
441Page* MemoryAllocator::FindLastPageInSameChunk(Page* p) {
442 int chunk_id = GetChunkId(p);
443 ASSERT(IsValidChunk(chunk_id));
444
445 Address chunk_start = chunks_[chunk_id].address();
446 size_t chunk_size = chunks_[chunk_id].size();
447
448 Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
449 ASSERT(chunk_start <= p->address() && p->address() < high);
450
451 return Page::FromAddress(high - Page::kPageSize);
452}
453
454
455#ifdef DEBUG
456void MemoryAllocator::ReportStatistics() {
457 float pct = static_cast<float>(capacity_ - size_) / capacity_;
458 PrintF(" capacity: %d, used: %d, available: %%%d\n\n",
459 capacity_, size_, static_cast<int>(pct*100));
460}
461#endif
462
463
464// -----------------------------------------------------------------------------
465// PagedSpace implementation
466
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000467PagedSpace::PagedSpace(int max_capacity,
468 AllocationSpace id,
469 Executability executable)
kasper.lund7276f142008-07-30 08:49:36 +0000470 : Space(id, executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000471 max_capacity_ = (RoundDown(max_capacity, Page::kPageSize) / Page::kPageSize)
472 * Page::kObjectAreaSize;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000473 accounting_stats_.Clear();
474
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000475 allocation_info_.top = NULL;
476 allocation_info_.limit = NULL;
477
478 mc_forwarding_info_.top = NULL;
479 mc_forwarding_info_.limit = NULL;
480}
481
482
483bool PagedSpace::Setup(Address start, size_t size) {
484 if (HasBeenSetup()) return false;
485
486 int num_pages = 0;
487 // Try to use the virtual memory range passed to us. If it is too small to
488 // contain at least one page, ignore it and allocate instead.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000489 int pages_in_chunk = PagesInChunk(start, size);
490 if (pages_in_chunk > 0) {
491 first_page_ = MemoryAllocator::CommitPages(RoundUp(start, Page::kPageSize),
492 Page::kPageSize * pages_in_chunk,
493 this, &num_pages);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000494 } else {
495 int requested_pages = Min(MemoryAllocator::kPagesPerChunk,
496 max_capacity_ / Page::kObjectAreaSize);
497 first_page_ =
498 MemoryAllocator::AllocatePages(requested_pages, &num_pages, this);
499 if (!first_page_->is_valid()) return false;
500 }
501
502 // We are sure that the first page is valid and that we have at least one
503 // page.
504 ASSERT(first_page_->is_valid());
505 ASSERT(num_pages > 0);
506 accounting_stats_.ExpandSpace(num_pages * Page::kObjectAreaSize);
507 ASSERT(Capacity() <= max_capacity_);
508
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000509 // Sequentially initialize remembered sets in the newly allocated
510 // pages and cache the current last page in the space.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000511 for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
512 p->ClearRSet();
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000513 last_page_ = p;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000514 }
515
516 // Use first_page_ for allocation.
517 SetAllocationInfo(&allocation_info_, first_page_);
518
519 return true;
520}
521
522
523bool PagedSpace::HasBeenSetup() {
524 return (Capacity() > 0);
525}
526
527
528void PagedSpace::TearDown() {
529 first_page_ = MemoryAllocator::FreePages(first_page_);
530 ASSERT(!first_page_->is_valid());
531
532 accounting_stats_.Clear();
533}
534
535
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000536#ifdef ENABLE_HEAP_PROTECTION
537
538void PagedSpace::Protect() {
539 Page* page = first_page_;
540 while (page->is_valid()) {
541 MemoryAllocator::ProtectChunkFromPage(page);
542 page = MemoryAllocator::FindLastPageInSameChunk(page)->next_page();
543 }
544}
545
546
547void PagedSpace::Unprotect() {
548 Page* page = first_page_;
549 while (page->is_valid()) {
550 MemoryAllocator::UnprotectChunkFromPage(page);
551 page = MemoryAllocator::FindLastPageInSameChunk(page)->next_page();
552 }
553}
554
555#endif
556
557
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000558void PagedSpace::ClearRSet() {
559 PageIterator it(this, PageIterator::ALL_PAGES);
560 while (it.has_next()) {
561 it.next()->ClearRSet();
562 }
563}
564
565
566Object* PagedSpace::FindObject(Address addr) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000567 // Note: this function can only be called before or after mark-compact GC
568 // because it accesses map pointers.
569 ASSERT(!MarkCompactCollector::in_use());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000570
571 if (!Contains(addr)) return Failure::Exception();
572
573 Page* p = Page::FromAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +0000574 ASSERT(IsUsed(p));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000575 Address cur = p->ObjectAreaStart();
576 Address end = p->AllocationTop();
577 while (cur < end) {
578 HeapObject* obj = HeapObject::FromAddress(cur);
579 Address next = cur + obj->Size();
580 if ((cur <= addr) && (addr < next)) return obj;
581 cur = next;
582 }
583
kasper.lund7276f142008-07-30 08:49:36 +0000584 UNREACHABLE();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000585 return Failure::Exception();
586}
587
588
kasper.lund7276f142008-07-30 08:49:36 +0000589bool PagedSpace::IsUsed(Page* page) {
590 PageIterator it(this, PageIterator::PAGES_IN_USE);
591 while (it.has_next()) {
592 if (page == it.next()) return true;
593 }
594 return false;
595}
596
597
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000598void PagedSpace::SetAllocationInfo(AllocationInfo* alloc_info, Page* p) {
599 alloc_info->top = p->ObjectAreaStart();
600 alloc_info->limit = p->ObjectAreaEnd();
kasper.lund7276f142008-07-30 08:49:36 +0000601 ASSERT(alloc_info->VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000602}
603
604
605void PagedSpace::MCResetRelocationInfo() {
606 // Set page indexes.
607 int i = 0;
608 PageIterator it(this, PageIterator::ALL_PAGES);
609 while (it.has_next()) {
610 Page* p = it.next();
611 p->mc_page_index = i++;
612 }
613
614 // Set mc_forwarding_info_ to the first page in the space.
615 SetAllocationInfo(&mc_forwarding_info_, first_page_);
616 // All the bytes in the space are 'available'. We will rediscover
617 // allocated and wasted bytes during GC.
618 accounting_stats_.Reset();
619}
620
621
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000622int PagedSpace::MCSpaceOffsetForAddress(Address addr) {
623#ifdef DEBUG
624 // The Contains function considers the address at the beginning of a
625 // page in the page, MCSpaceOffsetForAddress considers it is in the
626 // previous page.
627 if (Page::IsAlignedToPageSize(addr)) {
628 ASSERT(Contains(addr - kPointerSize));
629 } else {
630 ASSERT(Contains(addr));
631 }
632#endif
633
634 // If addr is at the end of a page, it belongs to previous page
635 Page* p = Page::IsAlignedToPageSize(addr)
636 ? Page::FromAllocationTop(addr)
637 : Page::FromAddress(addr);
638 int index = p->mc_page_index;
639 return (index * Page::kPageSize) + p->Offset(addr);
640}
641
642
kasper.lund7276f142008-07-30 08:49:36 +0000643// Slow case for reallocating and promoting objects during a compacting
644// collection. This function is not space-specific.
645HeapObject* PagedSpace::SlowMCAllocateRaw(int size_in_bytes) {
646 Page* current_page = TopPageOf(mc_forwarding_info_);
647 if (!current_page->next_page()->is_valid()) {
648 if (!Expand(current_page)) {
649 return NULL;
650 }
651 }
652
653 // There are surely more pages in the space now.
654 ASSERT(current_page->next_page()->is_valid());
655 // We do not add the top of page block for current page to the space's
656 // free list---the block may contain live objects so we cannot write
657 // bookkeeping information to it. Instead, we will recover top of page
658 // blocks when we move objects to their new locations.
659 //
660 // We do however write the allocation pointer to the page. The encoding
661 // of forwarding addresses is as an offset in terms of live bytes, so we
662 // need quick access to the allocation top of each page to decode
663 // forwarding addresses.
664 current_page->mc_relocation_top = mc_forwarding_info_.top;
665 SetAllocationInfo(&mc_forwarding_info_, current_page->next_page());
666 return AllocateLinearly(&mc_forwarding_info_, size_in_bytes);
667}
668
669
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000670bool PagedSpace::Expand(Page* last_page) {
671 ASSERT(max_capacity_ % Page::kObjectAreaSize == 0);
672 ASSERT(Capacity() % Page::kObjectAreaSize == 0);
673
674 if (Capacity() == max_capacity_) return false;
675
676 ASSERT(Capacity() < max_capacity_);
677 // Last page must be valid and its next page is invalid.
678 ASSERT(last_page->is_valid() && !last_page->next_page()->is_valid());
679
680 int available_pages = (max_capacity_ - Capacity()) / Page::kObjectAreaSize;
681 if (available_pages <= 0) return false;
682
683 int desired_pages = Min(available_pages, MemoryAllocator::kPagesPerChunk);
684 Page* p = MemoryAllocator::AllocatePages(desired_pages, &desired_pages, this);
685 if (!p->is_valid()) return false;
686
687 accounting_stats_.ExpandSpace(desired_pages * Page::kObjectAreaSize);
688 ASSERT(Capacity() <= max_capacity_);
689
690 MemoryAllocator::SetNextPage(last_page, p);
691
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000692 // Sequentially clear remembered set of new pages and and cache the
693 // new last page in the space.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000694 while (p->is_valid()) {
695 p->ClearRSet();
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000696 last_page_ = p;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000697 p = p->next_page();
698 }
699
700 return true;
701}
702
703
704#ifdef DEBUG
705int PagedSpace::CountTotalPages() {
706 int count = 0;
707 for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
708 count++;
709 }
710 return count;
711}
712#endif
713
714
715void PagedSpace::Shrink() {
716 // Release half of free pages.
717 Page* top_page = AllocationTopPage();
718 ASSERT(top_page->is_valid());
719
720 // Loop over the pages from the top page to the end of the space to count
721 // the number of pages to keep and find the last page to keep.
722 int free_pages = 0;
723 int pages_to_keep = 0; // Of the free pages.
724 Page* last_page_to_keep = top_page;
725 Page* current_page = top_page->next_page();
726 // Loop over the pages to the end of the space.
727 while (current_page->is_valid()) {
kasper.lund7276f142008-07-30 08:49:36 +0000728 // Advance last_page_to_keep every other step to end up at the midpoint.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000729 if ((free_pages & 0x1) == 1) {
730 pages_to_keep++;
731 last_page_to_keep = last_page_to_keep->next_page();
732 }
733 free_pages++;
734 current_page = current_page->next_page();
735 }
736
737 // Free pages after last_page_to_keep, and adjust the next_page link.
738 Page* p = MemoryAllocator::FreePages(last_page_to_keep->next_page());
739 MemoryAllocator::SetNextPage(last_page_to_keep, p);
740
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000741 // Since pages are only freed in whole chunks, we may have kept more
742 // than pages_to_keep. Count the extra pages and cache the new last
743 // page in the space.
744 last_page_ = last_page_to_keep;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000745 while (p->is_valid()) {
746 pages_to_keep++;
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000747 last_page_ = p;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000748 p = p->next_page();
749 }
750
751 // The difference between free_pages and pages_to_keep is the number of
752 // pages actually freed.
753 ASSERT(pages_to_keep <= free_pages);
754 int bytes_freed = (free_pages - pages_to_keep) * Page::kObjectAreaSize;
755 accounting_stats_.ShrinkSpace(bytes_freed);
756
757 ASSERT(Capacity() == CountTotalPages() * Page::kObjectAreaSize);
758}
759
760
761bool PagedSpace::EnsureCapacity(int capacity) {
762 if (Capacity() >= capacity) return true;
763
764 // Start from the allocation top and loop to the last page in the space.
765 Page* last_page = AllocationTopPage();
766 Page* next_page = last_page->next_page();
767 while (next_page->is_valid()) {
768 last_page = MemoryAllocator::FindLastPageInSameChunk(next_page);
769 next_page = last_page->next_page();
770 }
771
772 // Expand the space until it has the required capacity or expansion fails.
773 do {
774 if (!Expand(last_page)) return false;
775 ASSERT(last_page->next_page()->is_valid());
776 last_page =
777 MemoryAllocator::FindLastPageInSameChunk(last_page->next_page());
778 } while (Capacity() < capacity);
779
780 return true;
781}
782
783
784#ifdef DEBUG
785void PagedSpace::Print() { }
786#endif
787
788
789// -----------------------------------------------------------------------------
790// NewSpace implementation
791
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000792
793bool NewSpace::Setup(Address start, int size) {
794 // Setup new space based on the preallocated memory block defined by
795 // start and size. The provided space is divided into two semi-spaces.
796 // To support fast containment testing in the new space, the size of
797 // this chunk must be a power of two and it must be aligned to its size.
798 int initial_semispace_capacity = Heap::InitialSemiSpaceSize();
799 int maximum_semispace_capacity = Heap::SemiSpaceSize();
800
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000801 ASSERT(initial_semispace_capacity <= maximum_semispace_capacity);
802 ASSERT(IsPowerOf2(maximum_semispace_capacity));
803 maximum_capacity_ = maximum_semispace_capacity;
804 capacity_ = initial_semispace_capacity;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000805
806 // Allocate and setup the histogram arrays if necessary.
807#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
808 allocated_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
809 promoted_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
810
811#define SET_NAME(name) allocated_histogram_[name].set_name(#name); \
812 promoted_histogram_[name].set_name(#name);
813 INSTANCE_TYPE_LIST(SET_NAME)
814#undef SET_NAME
815#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000816
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000817 ASSERT(size == 2 * maximum_capacity_);
818 ASSERT(IsAddressAligned(start, size, 0));
819
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000820 if (!to_space_.Setup(start, capacity_, maximum_capacity_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000821 return false;
822 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000823 if (!from_space_.Setup(start + maximum_capacity_,
824 capacity_,
825 maximum_capacity_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000826 return false;
827 }
828
829 start_ = start;
830 address_mask_ = ~(size - 1);
831 object_mask_ = address_mask_ | kHeapObjectTag;
ager@chromium.org9085a012009-05-11 19:22:57 +0000832 object_expected_ = reinterpret_cast<uintptr_t>(start) | kHeapObjectTag;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000833
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000834 allocation_info_.top = to_space_.low();
835 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000836 mc_forwarding_info_.top = NULL;
837 mc_forwarding_info_.limit = NULL;
838
839 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
840 return true;
841}
842
843
844void NewSpace::TearDown() {
845#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
846 if (allocated_histogram_) {
847 DeleteArray(allocated_histogram_);
848 allocated_histogram_ = NULL;
849 }
850 if (promoted_histogram_) {
851 DeleteArray(promoted_histogram_);
852 promoted_histogram_ = NULL;
853 }
854#endif
855
856 start_ = NULL;
857 capacity_ = 0;
858 allocation_info_.top = NULL;
859 allocation_info_.limit = NULL;
860 mc_forwarding_info_.top = NULL;
861 mc_forwarding_info_.limit = NULL;
862
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000863 to_space_.TearDown();
864 from_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000865}
866
867
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000868#ifdef ENABLE_HEAP_PROTECTION
869
870void NewSpace::Protect() {
871 MemoryAllocator::Protect(ToSpaceLow(), Capacity());
872 MemoryAllocator::Protect(FromSpaceLow(), Capacity());
873}
874
875
876void NewSpace::Unprotect() {
877 MemoryAllocator::Unprotect(ToSpaceLow(), Capacity(),
878 to_space_.executable());
879 MemoryAllocator::Unprotect(FromSpaceLow(), Capacity(),
880 from_space_.executable());
881}
882
883#endif
884
885
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000886void NewSpace::Flip() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000887 SemiSpace tmp = from_space_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000888 from_space_ = to_space_;
889 to_space_ = tmp;
890}
891
892
893bool NewSpace::Double() {
894 ASSERT(capacity_ <= maximum_capacity_ / 2);
895 // TODO(1240712): Failure to double the from space can result in
896 // semispaces of different sizes. In the event of that failure, the
897 // to space doubling should be rolled back before returning false.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000898 if (!to_space_.Double() || !from_space_.Double()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000899 capacity_ *= 2;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000900 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000901 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
902 return true;
903}
904
905
906void NewSpace::ResetAllocationInfo() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000907 allocation_info_.top = to_space_.low();
908 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000909 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
910}
911
912
913void NewSpace::MCResetRelocationInfo() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000914 mc_forwarding_info_.top = from_space_.low();
915 mc_forwarding_info_.limit = from_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000916 ASSERT_SEMISPACE_ALLOCATION_INFO(mc_forwarding_info_, from_space_);
917}
918
919
920void NewSpace::MCCommitRelocationInfo() {
921 // Assumes that the spaces have been flipped so that mc_forwarding_info_ is
922 // valid allocation info for the to space.
923 allocation_info_.top = mc_forwarding_info_.top;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000924 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000925 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
926}
927
928
929#ifdef DEBUG
930// We do not use the SemispaceIterator because verification doesn't assume
931// that it works (it depends on the invariants we are checking).
932void NewSpace::Verify() {
933 // The allocation pointer should be in the space or at the very end.
934 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
935
936 // There should be objects packed in from the low address up to the
937 // allocation pointer.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000938 Address current = to_space_.low();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000939 while (current < top()) {
940 HeapObject* object = HeapObject::FromAddress(current);
941
942 // The first word should be a map, and we expect all map pointers to
943 // be in map space.
944 Map* map = object->map();
945 ASSERT(map->IsMap());
946 ASSERT(Heap::map_space()->Contains(map));
947
948 // The object should not be code or a map.
949 ASSERT(!object->IsMap());
950 ASSERT(!object->IsCode());
951
952 // The object itself should look OK.
953 object->Verify();
954
955 // All the interior pointers should be contained in the heap.
956 VerifyPointersVisitor visitor;
957 int size = object->Size();
958 object->IterateBody(map->instance_type(), size, &visitor);
959
960 current += size;
961 }
962
963 // The allocation pointer should not be in the middle of an object.
964 ASSERT(current == top());
965}
966#endif
967
968
969// -----------------------------------------------------------------------------
970// SemiSpace implementation
971
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000972bool SemiSpace::Setup(Address start,
973 int initial_capacity,
974 int maximum_capacity) {
975 // Creates a space in the young generation. The constructor does not
976 // allocate memory from the OS. A SemiSpace is given a contiguous chunk of
977 // memory of size 'capacity' when set up, and does not grow or shrink
978 // otherwise. In the mark-compact collector, the memory region of the from
979 // space is used as the marking stack. It requires contiguous memory
980 // addresses.
981 capacity_ = initial_capacity;
982 maximum_capacity_ = maximum_capacity;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000983
kasper.lund7276f142008-07-30 08:49:36 +0000984 if (!MemoryAllocator::CommitBlock(start, capacity_, executable())) {
985 return false;
986 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000987
988 start_ = start;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000989 address_mask_ = ~(maximum_capacity - 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000990 object_mask_ = address_mask_ | kHeapObjectTag;
ager@chromium.org9085a012009-05-11 19:22:57 +0000991 object_expected_ = reinterpret_cast<uintptr_t>(start) | kHeapObjectTag;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000992
993 age_mark_ = start_;
994 return true;
995}
996
997
998void SemiSpace::TearDown() {
999 start_ = NULL;
1000 capacity_ = 0;
1001}
1002
1003
1004bool SemiSpace::Double() {
kasper.lund7276f142008-07-30 08:49:36 +00001005 if (!MemoryAllocator::CommitBlock(high(), capacity_, executable())) {
1006 return false;
1007 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001008 capacity_ *= 2;
1009 return true;
1010}
1011
1012
1013#ifdef DEBUG
1014void SemiSpace::Print() { }
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001015
1016
1017void SemiSpace::Verify() { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001018#endif
1019
1020
1021// -----------------------------------------------------------------------------
1022// SemiSpaceIterator implementation.
1023SemiSpaceIterator::SemiSpaceIterator(NewSpace* space) {
1024 Initialize(space, space->bottom(), space->top(), NULL);
1025}
1026
1027
1028SemiSpaceIterator::SemiSpaceIterator(NewSpace* space,
1029 HeapObjectCallback size_func) {
1030 Initialize(space, space->bottom(), space->top(), size_func);
1031}
1032
1033
1034SemiSpaceIterator::SemiSpaceIterator(NewSpace* space, Address start) {
1035 Initialize(space, start, space->top(), NULL);
1036}
1037
1038
1039void SemiSpaceIterator::Initialize(NewSpace* space, Address start,
1040 Address end,
1041 HeapObjectCallback size_func) {
1042 ASSERT(space->ToSpaceContains(start));
1043 ASSERT(space->ToSpaceLow() <= end
1044 && end <= space->ToSpaceHigh());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001045 space_ = &space->to_space_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001046 current_ = start;
1047 limit_ = end;
1048 size_func_ = size_func;
1049}
1050
1051
1052#ifdef DEBUG
1053// A static array of histogram info for each type.
1054static HistogramInfo heap_histograms[LAST_TYPE+1];
1055static JSObject::SpillInformation js_spill_information;
1056
1057// heap_histograms is shared, always clear it before using it.
1058static void ClearHistograms() {
1059 // We reset the name each time, though it hasn't changed.
1060#define DEF_TYPE_NAME(name) heap_histograms[name].set_name(#name);
1061 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
1062#undef DEF_TYPE_NAME
1063
1064#define CLEAR_HISTOGRAM(name) heap_histograms[name].clear();
1065 INSTANCE_TYPE_LIST(CLEAR_HISTOGRAM)
1066#undef CLEAR_HISTOGRAM
1067
1068 js_spill_information.Clear();
1069}
1070
1071
1072static int code_kind_statistics[Code::NUMBER_OF_KINDS];
1073
1074
1075static void ClearCodeKindStatistics() {
1076 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1077 code_kind_statistics[i] = 0;
1078 }
1079}
1080
1081
1082static void ReportCodeKindStatistics() {
1083 const char* table[Code::NUMBER_OF_KINDS];
1084
1085#define CASE(name) \
1086 case Code::name: table[Code::name] = #name; \
1087 break
1088
1089 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1090 switch (static_cast<Code::Kind>(i)) {
1091 CASE(FUNCTION);
1092 CASE(STUB);
1093 CASE(BUILTIN);
1094 CASE(LOAD_IC);
1095 CASE(KEYED_LOAD_IC);
1096 CASE(STORE_IC);
1097 CASE(KEYED_STORE_IC);
1098 CASE(CALL_IC);
1099 }
1100 }
1101
1102#undef CASE
1103
1104 PrintF("\n Code kind histograms: \n");
1105 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1106 if (code_kind_statistics[i] > 0) {
1107 PrintF(" %-20s: %10d bytes\n", table[i], code_kind_statistics[i]);
1108 }
1109 }
1110 PrintF("\n");
1111}
1112
1113
1114static int CollectHistogramInfo(HeapObject* obj) {
1115 InstanceType type = obj->map()->instance_type();
1116 ASSERT(0 <= type && type <= LAST_TYPE);
1117 ASSERT(heap_histograms[type].name() != NULL);
1118 heap_histograms[type].increment_number(1);
1119 heap_histograms[type].increment_bytes(obj->Size());
1120
1121 if (FLAG_collect_heap_spill_statistics && obj->IsJSObject()) {
1122 JSObject::cast(obj)->IncrementSpillStatistics(&js_spill_information);
1123 }
1124
1125 return obj->Size();
1126}
1127
1128
1129static void ReportHistogram(bool print_spill) {
1130 PrintF("\n Object Histogram:\n");
1131 for (int i = 0; i <= LAST_TYPE; i++) {
1132 if (heap_histograms[i].number() > 0) {
1133 PrintF(" %-33s%10d (%10d bytes)\n",
1134 heap_histograms[i].name(),
1135 heap_histograms[i].number(),
1136 heap_histograms[i].bytes());
1137 }
1138 }
1139 PrintF("\n");
1140
1141 // Summarize string types.
1142 int string_number = 0;
1143 int string_bytes = 0;
1144#define INCREMENT(type, size, name) \
1145 string_number += heap_histograms[type].number(); \
1146 string_bytes += heap_histograms[type].bytes();
1147 STRING_TYPE_LIST(INCREMENT)
1148#undef INCREMENT
1149 if (string_number > 0) {
1150 PrintF(" %-33s%10d (%10d bytes)\n\n", "STRING_TYPE", string_number,
1151 string_bytes);
1152 }
1153
1154 if (FLAG_collect_heap_spill_statistics && print_spill) {
1155 js_spill_information.Print();
1156 }
1157}
1158#endif // DEBUG
1159
1160
1161// Support for statistics gathering for --heap-stats and --log-gc.
1162#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1163void NewSpace::ClearHistograms() {
1164 for (int i = 0; i <= LAST_TYPE; i++) {
1165 allocated_histogram_[i].clear();
1166 promoted_histogram_[i].clear();
1167 }
1168}
1169
1170// Because the copying collector does not touch garbage objects, we iterate
1171// the new space before a collection to get a histogram of allocated objects.
1172// This only happens (1) when compiled with DEBUG and the --heap-stats flag is
1173// set, or when compiled with ENABLE_LOGGING_AND_PROFILING and the --log-gc
1174// flag is set.
1175void NewSpace::CollectStatistics() {
1176 ClearHistograms();
1177 SemiSpaceIterator it(this);
1178 while (it.has_next()) RecordAllocation(it.next());
1179}
1180
1181
1182#ifdef ENABLE_LOGGING_AND_PROFILING
1183static void DoReportStatistics(HistogramInfo* info, const char* description) {
1184 LOG(HeapSampleBeginEvent("NewSpace", description));
1185 // Lump all the string types together.
1186 int string_number = 0;
1187 int string_bytes = 0;
1188#define INCREMENT(type, size, name) \
1189 string_number += info[type].number(); \
1190 string_bytes += info[type].bytes();
1191 STRING_TYPE_LIST(INCREMENT)
1192#undef INCREMENT
1193 if (string_number > 0) {
1194 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
1195 }
1196
1197 // Then do the other types.
1198 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
1199 if (info[i].number() > 0) {
1200 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
1201 info[i].bytes()));
1202 }
1203 }
1204 LOG(HeapSampleEndEvent("NewSpace", description));
1205}
1206#endif // ENABLE_LOGGING_AND_PROFILING
1207
1208
1209void NewSpace::ReportStatistics() {
1210#ifdef DEBUG
1211 if (FLAG_heap_stats) {
1212 float pct = static_cast<float>(Available()) / Capacity();
1213 PrintF(" capacity: %d, available: %d, %%%d\n",
1214 Capacity(), Available(), static_cast<int>(pct*100));
1215 PrintF("\n Object Histogram:\n");
1216 for (int i = 0; i <= LAST_TYPE; i++) {
1217 if (allocated_histogram_[i].number() > 0) {
1218 PrintF(" %-33s%10d (%10d bytes)\n",
1219 allocated_histogram_[i].name(),
1220 allocated_histogram_[i].number(),
1221 allocated_histogram_[i].bytes());
1222 }
1223 }
1224 PrintF("\n");
1225 }
1226#endif // DEBUG
1227
1228#ifdef ENABLE_LOGGING_AND_PROFILING
1229 if (FLAG_log_gc) {
1230 DoReportStatistics(allocated_histogram_, "allocated");
1231 DoReportStatistics(promoted_histogram_, "promoted");
1232 }
1233#endif // ENABLE_LOGGING_AND_PROFILING
1234}
1235
1236
1237void NewSpace::RecordAllocation(HeapObject* obj) {
1238 InstanceType type = obj->map()->instance_type();
1239 ASSERT(0 <= type && type <= LAST_TYPE);
1240 allocated_histogram_[type].increment_number(1);
1241 allocated_histogram_[type].increment_bytes(obj->Size());
1242}
1243
1244
1245void NewSpace::RecordPromotion(HeapObject* obj) {
1246 InstanceType type = obj->map()->instance_type();
1247 ASSERT(0 <= type && type <= LAST_TYPE);
1248 promoted_histogram_[type].increment_number(1);
1249 promoted_histogram_[type].increment_bytes(obj->Size());
1250}
1251#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1252
1253
1254// -----------------------------------------------------------------------------
1255// Free lists for old object spaces implementation
1256
1257void FreeListNode::set_size(int size_in_bytes) {
1258 ASSERT(size_in_bytes > 0);
1259 ASSERT(IsAligned(size_in_bytes, kPointerSize));
1260
1261 // We write a map and possibly size information to the block. If the block
1262 // is big enough to be a ByteArray with at least one extra word (the next
1263 // pointer), we set its map to be the byte array map and its size to an
1264 // appropriate array length for the desired size from HeapObject::Size().
1265 // If the block is too small (eg, one or two words), to hold both a size
1266 // field and a next pointer, we give it a filler map that gives it the
1267 // correct size.
1268 if (size_in_bytes > Array::kHeaderSize) {
1269 set_map(Heap::byte_array_map());
1270 ByteArray::cast(this)->set_length(ByteArray::LengthFor(size_in_bytes));
1271 } else if (size_in_bytes == kPointerSize) {
1272 set_map(Heap::one_word_filler_map());
1273 } else if (size_in_bytes == 2 * kPointerSize) {
1274 set_map(Heap::two_word_filler_map());
1275 } else {
1276 UNREACHABLE();
1277 }
kasper.lund7276f142008-07-30 08:49:36 +00001278 ASSERT(Size() == size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001279}
1280
1281
1282Address FreeListNode::next() {
1283 ASSERT(map() == Heap::byte_array_map());
kasper.lund7276f142008-07-30 08:49:36 +00001284 ASSERT(Size() >= kNextOffset + kPointerSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001285 return Memory::Address_at(address() + kNextOffset);
1286}
1287
1288
1289void FreeListNode::set_next(Address next) {
1290 ASSERT(map() == Heap::byte_array_map());
kasper.lund7276f142008-07-30 08:49:36 +00001291 ASSERT(Size() >= kNextOffset + kPointerSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001292 Memory::Address_at(address() + kNextOffset) = next;
1293}
1294
1295
1296OldSpaceFreeList::OldSpaceFreeList(AllocationSpace owner) : owner_(owner) {
1297 Reset();
1298}
1299
1300
1301void OldSpaceFreeList::Reset() {
1302 available_ = 0;
1303 for (int i = 0; i < kFreeListsLength; i++) {
1304 free_[i].head_node_ = NULL;
1305 }
1306 needs_rebuild_ = false;
1307 finger_ = kHead;
1308 free_[kHead].next_size_ = kEnd;
1309}
1310
1311
1312void OldSpaceFreeList::RebuildSizeList() {
1313 ASSERT(needs_rebuild_);
1314 int cur = kHead;
1315 for (int i = cur + 1; i < kFreeListsLength; i++) {
1316 if (free_[i].head_node_ != NULL) {
1317 free_[cur].next_size_ = i;
1318 cur = i;
1319 }
1320 }
1321 free_[cur].next_size_ = kEnd;
1322 needs_rebuild_ = false;
1323}
1324
1325
1326int OldSpaceFreeList::Free(Address start, int size_in_bytes) {
1327#ifdef DEBUG
1328 for (int i = 0; i < size_in_bytes; i += kPointerSize) {
1329 Memory::Address_at(start + i) = kZapValue;
1330 }
1331#endif
1332 FreeListNode* node = FreeListNode::FromAddress(start);
1333 node->set_size(size_in_bytes);
1334
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001335 // We don't use the freelists in compacting mode. This makes it more like a
1336 // GC that only has mark-sweep-compact and doesn't have a mark-sweep
1337 // collector.
1338 if (FLAG_always_compact) {
1339 return size_in_bytes;
1340 }
1341
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001342 // Early return to drop too-small blocks on the floor (one or two word
1343 // blocks cannot hold a map pointer, a size field, and a pointer to the
1344 // next block in the free list).
1345 if (size_in_bytes < kMinBlockSize) {
1346 return size_in_bytes;
1347 }
1348
1349 // Insert other blocks at the head of an exact free list.
1350 int index = size_in_bytes >> kPointerSizeLog2;
1351 node->set_next(free_[index].head_node_);
1352 free_[index].head_node_ = node->address();
1353 available_ += size_in_bytes;
1354 needs_rebuild_ = true;
1355 return 0;
1356}
1357
1358
1359Object* OldSpaceFreeList::Allocate(int size_in_bytes, int* wasted_bytes) {
1360 ASSERT(0 < size_in_bytes);
1361 ASSERT(size_in_bytes <= kMaxBlockSize);
1362 ASSERT(IsAligned(size_in_bytes, kPointerSize));
1363
1364 if (needs_rebuild_) RebuildSizeList();
1365 int index = size_in_bytes >> kPointerSizeLog2;
1366 // Check for a perfect fit.
1367 if (free_[index].head_node_ != NULL) {
1368 FreeListNode* node = FreeListNode::FromAddress(free_[index].head_node_);
1369 // If this was the last block of its size, remove the size.
1370 if ((free_[index].head_node_ = node->next()) == NULL) RemoveSize(index);
1371 available_ -= size_in_bytes;
1372 *wasted_bytes = 0;
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001373 ASSERT(!FLAG_always_compact); // We only use the freelists with mark-sweep.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001374 return node;
1375 }
1376 // Search the size list for the best fit.
1377 int prev = finger_ < index ? finger_ : kHead;
1378 int cur = FindSize(index, &prev);
1379 ASSERT(index < cur);
1380 if (cur == kEnd) {
1381 // No large enough size in list.
1382 *wasted_bytes = 0;
1383 return Failure::RetryAfterGC(size_in_bytes, owner_);
1384 }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001385 ASSERT(!FLAG_always_compact); // We only use the freelists with mark-sweep.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001386 int rem = cur - index;
1387 int rem_bytes = rem << kPointerSizeLog2;
1388 FreeListNode* cur_node = FreeListNode::FromAddress(free_[cur].head_node_);
kasper.lund7276f142008-07-30 08:49:36 +00001389 ASSERT(cur_node->Size() == (cur << kPointerSizeLog2));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001390 FreeListNode* rem_node = FreeListNode::FromAddress(free_[cur].head_node_ +
1391 size_in_bytes);
1392 // Distinguish the cases prev < rem < cur and rem <= prev < cur
1393 // to avoid many redundant tests and calls to Insert/RemoveSize.
1394 if (prev < rem) {
1395 // Simple case: insert rem between prev and cur.
1396 finger_ = prev;
1397 free_[prev].next_size_ = rem;
1398 // If this was the last block of size cur, remove the size.
1399 if ((free_[cur].head_node_ = cur_node->next()) == NULL) {
1400 free_[rem].next_size_ = free_[cur].next_size_;
1401 } else {
1402 free_[rem].next_size_ = cur;
1403 }
1404 // Add the remainder block.
1405 rem_node->set_size(rem_bytes);
1406 rem_node->set_next(free_[rem].head_node_);
1407 free_[rem].head_node_ = rem_node->address();
1408 } else {
1409 // If this was the last block of size cur, remove the size.
1410 if ((free_[cur].head_node_ = cur_node->next()) == NULL) {
1411 finger_ = prev;
1412 free_[prev].next_size_ = free_[cur].next_size_;
1413 }
1414 if (rem_bytes < kMinBlockSize) {
1415 // Too-small remainder is wasted.
1416 rem_node->set_size(rem_bytes);
1417 available_ -= size_in_bytes + rem_bytes;
1418 *wasted_bytes = rem_bytes;
1419 return cur_node;
1420 }
1421 // Add the remainder block and, if needed, insert its size.
1422 rem_node->set_size(rem_bytes);
1423 rem_node->set_next(free_[rem].head_node_);
1424 free_[rem].head_node_ = rem_node->address();
1425 if (rem_node->next() == NULL) InsertSize(rem);
1426 }
1427 available_ -= size_in_bytes;
1428 *wasted_bytes = 0;
1429 return cur_node;
1430}
1431
1432
kasper.lund7276f142008-07-30 08:49:36 +00001433#ifdef DEBUG
1434bool OldSpaceFreeList::Contains(FreeListNode* node) {
1435 for (int i = 0; i < kFreeListsLength; i++) {
1436 Address cur_addr = free_[i].head_node_;
1437 while (cur_addr != NULL) {
1438 FreeListNode* cur_node = FreeListNode::FromAddress(cur_addr);
1439 if (cur_node == node) return true;
1440 cur_addr = cur_node->next();
1441 }
1442 }
1443 return false;
1444}
1445#endif
1446
1447
1448MapSpaceFreeList::MapSpaceFreeList(AllocationSpace owner) {
1449 owner_ = owner;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001450 Reset();
1451}
1452
1453
1454void MapSpaceFreeList::Reset() {
1455 available_ = 0;
1456 head_ = NULL;
1457}
1458
1459
1460void MapSpaceFreeList::Free(Address start) {
1461#ifdef DEBUG
1462 for (int i = 0; i < Map::kSize; i += kPointerSize) {
1463 Memory::Address_at(start + i) = kZapValue;
1464 }
1465#endif
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001466 ASSERT(!FLAG_always_compact); // We only use the freelists with mark-sweep.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001467 FreeListNode* node = FreeListNode::FromAddress(start);
1468 node->set_size(Map::kSize);
1469 node->set_next(head_);
1470 head_ = node->address();
1471 available_ += Map::kSize;
1472}
1473
1474
1475Object* MapSpaceFreeList::Allocate() {
1476 if (head_ == NULL) {
kasper.lund7276f142008-07-30 08:49:36 +00001477 return Failure::RetryAfterGC(Map::kSize, owner_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001478 }
1479
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001480 ASSERT(!FLAG_always_compact); // We only use the freelists with mark-sweep.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001481 FreeListNode* node = FreeListNode::FromAddress(head_);
1482 head_ = node->next();
1483 available_ -= Map::kSize;
1484 return node;
1485}
1486
1487
1488// -----------------------------------------------------------------------------
1489// OldSpace implementation
1490
1491void OldSpace::PrepareForMarkCompact(bool will_compact) {
1492 if (will_compact) {
1493 // Reset relocation info. During a compacting collection, everything in
1494 // the space is considered 'available' and we will rediscover live data
1495 // and waste during the collection.
1496 MCResetRelocationInfo();
1497 mc_end_of_relocation_ = bottom();
1498 ASSERT(Available() == Capacity());
1499 } else {
1500 // During a non-compacting collection, everything below the linear
1501 // allocation pointer is considered allocated (everything above is
1502 // available) and we will rediscover available and wasted bytes during
1503 // the collection.
1504 accounting_stats_.AllocateBytes(free_list_.available());
1505 accounting_stats_.FillWastedBytes(Waste());
1506 }
1507
kasper.lund7276f142008-07-30 08:49:36 +00001508 // Clear the free list before a full GC---it will be rebuilt afterward.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001509 free_list_.Reset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001510}
1511
1512
1513void OldSpace::MCAdjustRelocationEnd(Address address, int size_in_bytes) {
1514 ASSERT(Contains(address));
1515 Address current_top = mc_end_of_relocation_;
1516 Page* current_page = Page::FromAllocationTop(current_top);
1517
1518 // No more objects relocated to this page? Move to the next.
1519 ASSERT(current_top <= current_page->mc_relocation_top);
1520 if (current_top == current_page->mc_relocation_top) {
1521 // The space should already be properly expanded.
1522 Page* next_page = current_page->next_page();
1523 CHECK(next_page->is_valid());
1524 mc_end_of_relocation_ = next_page->ObjectAreaStart();
1525 }
1526 ASSERT(mc_end_of_relocation_ == address);
1527 mc_end_of_relocation_ += size_in_bytes;
1528}
1529
1530
1531void OldSpace::MCCommitRelocationInfo() {
1532 // Update fast allocation info.
1533 allocation_info_.top = mc_forwarding_info_.top;
1534 allocation_info_.limit = mc_forwarding_info_.limit;
kasper.lund7276f142008-07-30 08:49:36 +00001535 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001536
1537 // The space is compacted and we haven't yet built free lists or
1538 // wasted any space.
1539 ASSERT(Waste() == 0);
1540 ASSERT(AvailableFree() == 0);
1541
1542 // Build the free list for the space.
1543 int computed_size = 0;
1544 PageIterator it(this, PageIterator::PAGES_USED_BY_MC);
1545 while (it.has_next()) {
1546 Page* p = it.next();
1547 // Space below the relocation pointer is allocated.
1548 computed_size += p->mc_relocation_top - p->ObjectAreaStart();
1549 if (it.has_next()) {
1550 // Free the space at the top of the page. We cannot use
1551 // p->mc_relocation_top after the call to Free (because Free will clear
1552 // remembered set bits).
1553 int extra_size = p->ObjectAreaEnd() - p->mc_relocation_top;
1554 if (extra_size > 0) {
1555 int wasted_bytes = free_list_.Free(p->mc_relocation_top, extra_size);
1556 // The bytes we have just "freed" to add to the free list were
1557 // already accounted as available.
1558 accounting_stats_.WasteBytes(wasted_bytes);
1559 }
1560 }
1561 }
1562
1563 // Make sure the computed size - based on the used portion of the pages in
1564 // use - matches the size obtained while computing forwarding addresses.
1565 ASSERT(computed_size == Size());
1566}
1567
1568
kasper.lund7276f142008-07-30 08:49:36 +00001569// Slow case for normal allocation. Try in order: (1) allocate in the next
1570// page in the space, (2) allocate off the space's free list, (3) expand the
1571// space, (4) fail.
1572HeapObject* OldSpace::SlowAllocateRaw(int size_in_bytes) {
1573 // Linear allocation in this space has failed. If there is another page
1574 // in the space, move to that page and allocate there. This allocation
1575 // should succeed (size_in_bytes should not be greater than a page's
1576 // object area size).
1577 Page* current_page = TopPageOf(allocation_info_);
1578 if (current_page->next_page()->is_valid()) {
1579 return AllocateInNextPage(current_page, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001580 }
kasper.lund7276f142008-07-30 08:49:36 +00001581
1582 // There is no next page in this space. Try free list allocation.
1583 int wasted_bytes;
1584 Object* result = free_list_.Allocate(size_in_bytes, &wasted_bytes);
1585 accounting_stats_.WasteBytes(wasted_bytes);
1586 if (!result->IsFailure()) {
1587 accounting_stats_.AllocateBytes(size_in_bytes);
1588 return HeapObject::cast(result);
1589 }
1590
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001591 // Free list allocation failed and there is no next page. Fail if we have
1592 // hit the old generation size limit that should cause a garbage
1593 // collection.
1594 if (!Heap::always_allocate() && Heap::OldGenerationAllocationLimitReached()) {
1595 return NULL;
1596 }
1597
1598 // Try to expand the space and allocate in the new next page.
kasper.lund7276f142008-07-30 08:49:36 +00001599 ASSERT(!current_page->next_page()->is_valid());
1600 if (Expand(current_page)) {
1601 return AllocateInNextPage(current_page, size_in_bytes);
1602 }
1603
1604 // Finally, fail.
1605 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001606}
1607
1608
kasper.lund7276f142008-07-30 08:49:36 +00001609// Add the block at the top of the page to the space's free list, set the
1610// allocation info to the next page (assumed to be one), and allocate
1611// linearly there.
1612HeapObject* OldSpace::AllocateInNextPage(Page* current_page,
1613 int size_in_bytes) {
1614 ASSERT(current_page->next_page()->is_valid());
1615 // Add the block at the top of this page to the free list.
1616 int free_size = current_page->ObjectAreaEnd() - allocation_info_.top;
1617 if (free_size > 0) {
1618 int wasted_bytes = free_list_.Free(allocation_info_.top, free_size);
1619 accounting_stats_.WasteBytes(wasted_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001620 }
kasper.lund7276f142008-07-30 08:49:36 +00001621 SetAllocationInfo(&allocation_info_, current_page->next_page());
1622 return AllocateLinearly(&allocation_info_, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001623}
1624
1625
1626#ifdef DEBUG
1627// We do not assume that the PageIterator works, because it depends on the
1628// invariants we are checking during verification.
1629void OldSpace::Verify() {
1630 // The allocation pointer should be valid, and it should be in a page in the
1631 // space.
kasper.lund7276f142008-07-30 08:49:36 +00001632 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001633 Page* top_page = Page::FromAllocationTop(allocation_info_.top);
1634 ASSERT(MemoryAllocator::IsPageInSpace(top_page, this));
1635
1636 // Loop over all the pages.
1637 bool above_allocation_top = false;
1638 Page* current_page = first_page_;
1639 while (current_page->is_valid()) {
1640 if (above_allocation_top) {
1641 // We don't care what's above the allocation top.
1642 } else {
1643 // Unless this is the last page in the space containing allocated
1644 // objects, the allocation top should be at the object area end.
1645 Address top = current_page->AllocationTop();
1646 if (current_page == top_page) {
1647 ASSERT(top == allocation_info_.top);
1648 // The next page will be above the allocation top.
1649 above_allocation_top = true;
1650 } else {
1651 ASSERT(top == current_page->ObjectAreaEnd());
1652 }
1653
1654 // It should be packed with objects from the bottom to the top.
1655 Address current = current_page->ObjectAreaStart();
1656 while (current < top) {
1657 HeapObject* object = HeapObject::FromAddress(current);
1658
1659 // The first word should be a map, and we expect all map pointers to
1660 // be in map space.
1661 Map* map = object->map();
1662 ASSERT(map->IsMap());
1663 ASSERT(Heap::map_space()->Contains(map));
1664
1665 // The object should not be a map.
1666 ASSERT(!object->IsMap());
1667
1668 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001669 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001670
1671 // All the interior pointers should be contained in the heap and have
1672 // their remembered set bits set if they point to new space. Code
1673 // objects do not have remembered set bits that we care about.
1674 VerifyPointersAndRSetVisitor rset_visitor;
1675 VerifyPointersVisitor no_rset_visitor;
1676 int size = object->Size();
1677 if (object->IsCode()) {
1678 Code::cast(object)->ConvertICTargetsFromAddressToObject();
1679 object->IterateBody(map->instance_type(), size, &no_rset_visitor);
1680 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
1681 } else {
1682 object->IterateBody(map->instance_type(), size, &rset_visitor);
1683 }
1684
1685 current += size;
1686 }
1687
1688 // The allocation pointer should not be in the middle of an object.
1689 ASSERT(current == top);
1690 }
1691
1692 current_page = current_page->next_page();
1693 }
1694}
1695
1696
1697struct CommentStatistic {
1698 const char* comment;
1699 int size;
1700 int count;
1701 void Clear() {
1702 comment = NULL;
1703 size = 0;
1704 count = 0;
1705 }
1706};
1707
1708
1709// must be small, since an iteration is used for lookup
1710const int kMaxComments = 64;
1711static CommentStatistic comments_statistics[kMaxComments+1];
1712
1713
1714void PagedSpace::ReportCodeStatistics() {
1715 ReportCodeKindStatistics();
1716 PrintF("Code comment statistics (\" [ comment-txt : size/ "
1717 "count (average)\"):\n");
1718 for (int i = 0; i <= kMaxComments; i++) {
1719 const CommentStatistic& cs = comments_statistics[i];
1720 if (cs.size > 0) {
1721 PrintF(" %-30s: %10d/%6d (%d)\n", cs.comment, cs.size, cs.count,
1722 cs.size/cs.count);
1723 }
1724 }
1725 PrintF("\n");
1726}
1727
1728
1729void PagedSpace::ResetCodeStatistics() {
1730 ClearCodeKindStatistics();
1731 for (int i = 0; i < kMaxComments; i++) comments_statistics[i].Clear();
1732 comments_statistics[kMaxComments].comment = "Unknown";
1733 comments_statistics[kMaxComments].size = 0;
1734 comments_statistics[kMaxComments].count = 0;
1735}
1736
1737
1738// Adds comment to 'comment_statistics' table. Performance OK sa long as
1739// 'kMaxComments' is small
1740static void EnterComment(const char* comment, int delta) {
1741 // Do not count empty comments
1742 if (delta <= 0) return;
1743 CommentStatistic* cs = &comments_statistics[kMaxComments];
1744 // Search for a free or matching entry in 'comments_statistics': 'cs'
1745 // points to result.
1746 for (int i = 0; i < kMaxComments; i++) {
1747 if (comments_statistics[i].comment == NULL) {
1748 cs = &comments_statistics[i];
1749 cs->comment = comment;
1750 break;
1751 } else if (strcmp(comments_statistics[i].comment, comment) == 0) {
1752 cs = &comments_statistics[i];
1753 break;
1754 }
1755 }
1756 // Update entry for 'comment'
1757 cs->size += delta;
1758 cs->count += 1;
1759}
1760
1761
1762// Call for each nested comment start (start marked with '[ xxx', end marked
1763// with ']'. RelocIterator 'it' must point to a comment reloc info.
1764static void CollectCommentStatistics(RelocIterator* it) {
1765 ASSERT(!it->done());
ager@chromium.org236ad962008-09-25 09:45:57 +00001766 ASSERT(it->rinfo()->rmode() == RelocInfo::COMMENT);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001767 const char* tmp = reinterpret_cast<const char*>(it->rinfo()->data());
1768 if (tmp[0] != '[') {
1769 // Not a nested comment; skip
1770 return;
1771 }
1772
1773 // Search for end of nested comment or a new nested comment
1774 const char* const comment_txt =
1775 reinterpret_cast<const char*>(it->rinfo()->data());
1776 const byte* prev_pc = it->rinfo()->pc();
1777 int flat_delta = 0;
1778 it->next();
1779 while (true) {
1780 // All nested comments must be terminated properly, and therefore exit
1781 // from loop.
1782 ASSERT(!it->done());
ager@chromium.org236ad962008-09-25 09:45:57 +00001783 if (it->rinfo()->rmode() == RelocInfo::COMMENT) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001784 const char* const txt =
1785 reinterpret_cast<const char*>(it->rinfo()->data());
1786 flat_delta += it->rinfo()->pc() - prev_pc;
1787 if (txt[0] == ']') break; // End of nested comment
1788 // A new comment
1789 CollectCommentStatistics(it);
1790 // Skip code that was covered with previous comment
1791 prev_pc = it->rinfo()->pc();
1792 }
1793 it->next();
1794 }
1795 EnterComment(comment_txt, flat_delta);
1796}
1797
1798
1799// Collects code size statistics:
1800// - by code kind
1801// - by code comment
1802void PagedSpace::CollectCodeStatistics() {
1803 HeapObjectIterator obj_it(this);
1804 while (obj_it.has_next()) {
1805 HeapObject* obj = obj_it.next();
1806 if (obj->IsCode()) {
1807 Code* code = Code::cast(obj);
1808 code_kind_statistics[code->kind()] += code->Size();
1809 RelocIterator it(code);
1810 int delta = 0;
1811 const byte* prev_pc = code->instruction_start();
1812 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001813 if (it.rinfo()->rmode() == RelocInfo::COMMENT) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001814 delta += it.rinfo()->pc() - prev_pc;
1815 CollectCommentStatistics(&it);
1816 prev_pc = it.rinfo()->pc();
1817 }
1818 it.next();
1819 }
1820
1821 ASSERT(code->instruction_start() <= prev_pc &&
1822 prev_pc <= code->relocation_start());
1823 delta += code->relocation_start() - prev_pc;
1824 EnterComment("NoComment", delta);
1825 }
1826 }
1827}
1828
1829
1830void OldSpace::ReportStatistics() {
1831 int pct = Available() * 100 / Capacity();
1832 PrintF(" capacity: %d, waste: %d, available: %d, %%%d\n",
1833 Capacity(), Waste(), Available(), pct);
1834
1835 // Report remembered set statistics.
1836 int rset_marked_pointers = 0;
1837 int rset_marked_arrays = 0;
1838 int rset_marked_array_elements = 0;
1839 int cross_gen_pointers = 0;
1840 int cross_gen_array_elements = 0;
1841
1842 PageIterator page_it(this, PageIterator::PAGES_IN_USE);
1843 while (page_it.has_next()) {
1844 Page* p = page_it.next();
1845
1846 for (Address rset_addr = p->RSetStart();
1847 rset_addr < p->RSetEnd();
1848 rset_addr += kIntSize) {
1849 int rset = Memory::int_at(rset_addr);
1850 if (rset != 0) {
1851 // Bits were set
1852 int intoff = rset_addr - p->address();
1853 int bitoff = 0;
1854 for (; bitoff < kBitsPerInt; ++bitoff) {
1855 if ((rset & (1 << bitoff)) != 0) {
1856 int bitpos = intoff*kBitsPerByte + bitoff;
1857 Address slot = p->OffsetToAddress(bitpos << kObjectAlignmentBits);
1858 Object** obj = reinterpret_cast<Object**>(slot);
1859 if (*obj == Heap::fixed_array_map()) {
1860 rset_marked_arrays++;
1861 FixedArray* fa = FixedArray::cast(HeapObject::FromAddress(slot));
1862
1863 rset_marked_array_elements += fa->length();
1864 // Manually inline FixedArray::IterateBody
1865 Address elm_start = slot + FixedArray::kHeaderSize;
1866 Address elm_stop = elm_start + fa->length() * kPointerSize;
1867 for (Address elm_addr = elm_start;
1868 elm_addr < elm_stop; elm_addr += kPointerSize) {
1869 // Filter non-heap-object pointers
1870 Object** elm_p = reinterpret_cast<Object**>(elm_addr);
1871 if (Heap::InNewSpace(*elm_p))
1872 cross_gen_array_elements++;
1873 }
1874 } else {
1875 rset_marked_pointers++;
1876 if (Heap::InNewSpace(*obj))
1877 cross_gen_pointers++;
1878 }
1879 }
1880 }
1881 }
1882 }
1883 }
1884
1885 pct = rset_marked_pointers == 0 ?
1886 0 : cross_gen_pointers * 100 / rset_marked_pointers;
1887 PrintF(" rset-marked pointers %d, to-new-space %d (%%%d)\n",
1888 rset_marked_pointers, cross_gen_pointers, pct);
1889 PrintF(" rset_marked arrays %d, ", rset_marked_arrays);
1890 PrintF(" elements %d, ", rset_marked_array_elements);
1891 pct = rset_marked_array_elements == 0 ? 0
1892 : cross_gen_array_elements * 100 / rset_marked_array_elements;
1893 PrintF(" pointers to new space %d (%%%d)\n", cross_gen_array_elements, pct);
1894 PrintF(" total rset-marked bits %d\n",
1895 (rset_marked_pointers + rset_marked_arrays));
1896 pct = (rset_marked_pointers + rset_marked_array_elements) == 0 ? 0
1897 : (cross_gen_pointers + cross_gen_array_elements) * 100 /
1898 (rset_marked_pointers + rset_marked_array_elements);
1899 PrintF(" total rset pointers %d, true cross generation ones %d (%%%d)\n",
1900 (rset_marked_pointers + rset_marked_array_elements),
1901 (cross_gen_pointers + cross_gen_array_elements),
1902 pct);
1903
1904 ClearHistograms();
1905 HeapObjectIterator obj_it(this);
1906 while (obj_it.has_next()) { CollectHistogramInfo(obj_it.next()); }
1907 ReportHistogram(true);
1908}
1909
1910
1911// Dump the range of remembered set words between [start, end) corresponding
1912// to the pointers starting at object_p. The allocation_top is an object
1913// pointer which should not be read past. This is important for large object
1914// pages, where some bits in the remembered set range do not correspond to
1915// allocated addresses.
1916static void PrintRSetRange(Address start, Address end, Object** object_p,
1917 Address allocation_top) {
1918 Address rset_address = start;
1919
1920 // If the range starts on on odd numbered word (eg, for large object extra
1921 // remembered set ranges), print some spaces.
ager@chromium.org9085a012009-05-11 19:22:57 +00001922 if ((reinterpret_cast<uintptr_t>(start) / kIntSize) % 2 == 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001923 PrintF(" ");
1924 }
1925
1926 // Loop over all the words in the range.
1927 while (rset_address < end) {
1928 uint32_t rset_word = Memory::uint32_at(rset_address);
1929 int bit_position = 0;
1930
1931 // Loop over all the bits in the word.
1932 while (bit_position < kBitsPerInt) {
1933 if (object_p == reinterpret_cast<Object**>(allocation_top)) {
1934 // Print a bar at the allocation pointer.
1935 PrintF("|");
1936 } else if (object_p > reinterpret_cast<Object**>(allocation_top)) {
1937 // Do not dereference object_p past the allocation pointer.
1938 PrintF("#");
1939 } else if ((rset_word & (1 << bit_position)) == 0) {
1940 // Print a dot for zero bits.
1941 PrintF(".");
1942 } else if (Heap::InNewSpace(*object_p)) {
1943 // Print an X for one bits for pointers to new space.
1944 PrintF("X");
1945 } else {
1946 // Print a circle for one bits for pointers to old space.
1947 PrintF("o");
1948 }
1949
1950 // Print a space after every 8th bit except the last.
1951 if (bit_position % 8 == 7 && bit_position != (kBitsPerInt - 1)) {
1952 PrintF(" ");
1953 }
1954
1955 // Advance to next bit.
1956 bit_position++;
1957 object_p++;
1958 }
1959
1960 // Print a newline after every odd numbered word, otherwise a space.
ager@chromium.org9085a012009-05-11 19:22:57 +00001961 if ((reinterpret_cast<uintptr_t>(rset_address) / kIntSize) % 2 == 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001962 PrintF("\n");
1963 } else {
1964 PrintF(" ");
1965 }
1966
1967 // Advance to next remembered set word.
1968 rset_address += kIntSize;
1969 }
1970}
1971
1972
1973void PagedSpace::DoPrintRSet(const char* space_name) {
1974 PageIterator it(this, PageIterator::PAGES_IN_USE);
1975 while (it.has_next()) {
1976 Page* p = it.next();
1977 PrintF("%s page 0x%x:\n", space_name, p);
1978 PrintRSetRange(p->RSetStart(), p->RSetEnd(),
1979 reinterpret_cast<Object**>(p->ObjectAreaStart()),
1980 p->AllocationTop());
1981 PrintF("\n");
1982 }
1983}
1984
1985
1986void OldSpace::PrintRSet() { DoPrintRSet("old"); }
1987#endif
1988
1989// -----------------------------------------------------------------------------
1990// MapSpace implementation
1991
1992void MapSpace::PrepareForMarkCompact(bool will_compact) {
1993 if (will_compact) {
1994 // Reset relocation info.
1995 MCResetRelocationInfo();
1996
1997 // Initialize map index entry.
1998 int page_count = 0;
1999 PageIterator it(this, PageIterator::ALL_PAGES);
2000 while (it.has_next()) {
2001 ASSERT_MAP_PAGE_INDEX(page_count);
2002
2003 Page* p = it.next();
2004 ASSERT(p->mc_page_index == page_count);
2005
2006 page_addresses_[page_count++] = p->address();
2007 }
2008
2009 // During a compacting collection, everything in the space is considered
2010 // 'available' (set by the call to MCResetRelocationInfo) and we will
2011 // rediscover live and wasted bytes during the collection.
2012 ASSERT(Available() == Capacity());
2013 } else {
2014 // During a non-compacting collection, everything below the linear
2015 // allocation pointer except wasted top-of-page blocks is considered
2016 // allocated and we will rediscover available bytes during the
2017 // collection.
2018 accounting_stats_.AllocateBytes(free_list_.available());
2019 }
2020
kasper.lund7276f142008-07-30 08:49:36 +00002021 // Clear the free list before a full GC---it will be rebuilt afterward.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002022 free_list_.Reset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002023}
2024
2025
2026void MapSpace::MCCommitRelocationInfo() {
2027 // Update fast allocation info.
2028 allocation_info_.top = mc_forwarding_info_.top;
2029 allocation_info_.limit = mc_forwarding_info_.limit;
kasper.lund7276f142008-07-30 08:49:36 +00002030 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002031
2032 // The space is compacted and we haven't yet wasted any space.
2033 ASSERT(Waste() == 0);
2034
2035 // Update allocation_top of each page in use and compute waste.
2036 int computed_size = 0;
2037 PageIterator it(this, PageIterator::PAGES_USED_BY_MC);
2038 while (it.has_next()) {
2039 Page* page = it.next();
2040 Address page_top = page->AllocationTop();
2041 computed_size += page_top - page->ObjectAreaStart();
2042 if (it.has_next()) {
2043 accounting_stats_.WasteBytes(page->ObjectAreaEnd() - page_top);
2044 }
2045 }
2046
2047 // Make sure the computed size - based on the used portion of the
2048 // pages in use - matches the size we adjust during allocation.
2049 ASSERT(computed_size == Size());
2050}
2051
2052
kasper.lund7276f142008-07-30 08:49:36 +00002053// Slow case for normal allocation. Try in order: (1) allocate in the next
2054// page in the space, (2) allocate off the space's free list, (3) expand the
2055// space, (4) fail.
2056HeapObject* MapSpace::SlowAllocateRaw(int size_in_bytes) {
2057 // Linear allocation in this space has failed. If there is another page
2058 // in the space, move to that page and allocate there. This allocation
2059 // should succeed.
2060 Page* current_page = TopPageOf(allocation_info_);
2061 if (current_page->next_page()->is_valid()) {
2062 return AllocateInNextPage(current_page, size_in_bytes);
2063 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002064
kasper.lund7276f142008-07-30 08:49:36 +00002065 // There is no next page in this space. Try free list allocation. The
2066 // map space free list implicitly assumes that all free blocks are map
2067 // sized.
2068 if (size_in_bytes == Map::kSize) {
2069 Object* result = free_list_.Allocate();
2070 if (!result->IsFailure()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002071 accounting_stats_.AllocateBytes(size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002072 return HeapObject::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002073 }
2074 }
kasper.lund7276f142008-07-30 08:49:36 +00002075
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002076 // Free list allocation failed and there is no next page. Fail if we have
2077 // hit the old generation size limit that should cause a garbage
2078 // collection.
2079 if (!Heap::always_allocate() && Heap::OldGenerationAllocationLimitReached()) {
2080 return NULL;
2081 }
2082
2083 // Try to expand the space and allocate in the new next page.
kasper.lund7276f142008-07-30 08:49:36 +00002084 ASSERT(!current_page->next_page()->is_valid());
2085 if (Expand(current_page)) {
2086 return AllocateInNextPage(current_page, size_in_bytes);
2087 }
2088
2089 // Finally, fail.
2090 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002091}
2092
2093
kasper.lund7276f142008-07-30 08:49:36 +00002094// Move to the next page (there is assumed to be one) and allocate there.
2095// The top of page block is always wasted, because it is too small to hold a
2096// map.
2097HeapObject* MapSpace::AllocateInNextPage(Page* current_page,
2098 int size_in_bytes) {
2099 ASSERT(current_page->next_page()->is_valid());
2100 ASSERT(current_page->ObjectAreaEnd() - allocation_info_.top == kPageExtra);
2101 accounting_stats_.WasteBytes(kPageExtra);
2102 SetAllocationInfo(&allocation_info_, current_page->next_page());
2103 return AllocateLinearly(&allocation_info_, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002104}
2105
2106
2107#ifdef DEBUG
2108// We do not assume that the PageIterator works, because it depends on the
2109// invariants we are checking during verification.
2110void MapSpace::Verify() {
2111 // The allocation pointer should be valid, and it should be in a page in the
2112 // space.
kasper.lund7276f142008-07-30 08:49:36 +00002113 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002114 Page* top_page = Page::FromAllocationTop(allocation_info_.top);
2115 ASSERT(MemoryAllocator::IsPageInSpace(top_page, this));
2116
2117 // Loop over all the pages.
2118 bool above_allocation_top = false;
2119 Page* current_page = first_page_;
2120 while (current_page->is_valid()) {
2121 if (above_allocation_top) {
2122 // We don't care what's above the allocation top.
2123 } else {
2124 // Unless this is the last page in the space containing allocated
2125 // objects, the allocation top should be at a constant offset from the
2126 // object area end.
2127 Address top = current_page->AllocationTop();
2128 if (current_page == top_page) {
2129 ASSERT(top == allocation_info_.top);
2130 // The next page will be above the allocation top.
2131 above_allocation_top = true;
2132 } else {
2133 ASSERT(top == current_page->ObjectAreaEnd() - kPageExtra);
2134 }
2135
2136 // It should be packed with objects from the bottom to the top.
2137 Address current = current_page->ObjectAreaStart();
2138 while (current < top) {
2139 HeapObject* object = HeapObject::FromAddress(current);
2140
2141 // The first word should be a map, and we expect all map pointers to
2142 // be in map space.
2143 Map* map = object->map();
2144 ASSERT(map->IsMap());
2145 ASSERT(Heap::map_space()->Contains(map));
2146
2147 // The object should be a map or a byte array.
2148 ASSERT(object->IsMap() || object->IsByteArray());
2149
2150 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002151 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002152
2153 // All the interior pointers should be contained in the heap and
2154 // have their remembered set bits set if they point to new space.
2155 VerifyPointersAndRSetVisitor visitor;
2156 int size = object->Size();
2157 object->IterateBody(map->instance_type(), size, &visitor);
2158
2159 current += size;
2160 }
2161
2162 // The allocation pointer should not be in the middle of an object.
2163 ASSERT(current == top);
2164 }
2165
2166 current_page = current_page->next_page();
2167 }
2168}
2169
2170
2171void MapSpace::ReportStatistics() {
2172 int pct = Available() * 100 / Capacity();
2173 PrintF(" capacity: %d, waste: %d, available: %d, %%%d\n",
2174 Capacity(), Waste(), Available(), pct);
2175
2176 // Report remembered set statistics.
2177 int rset_marked_pointers = 0;
2178 int cross_gen_pointers = 0;
2179
2180 PageIterator page_it(this, PageIterator::PAGES_IN_USE);
2181 while (page_it.has_next()) {
2182 Page* p = page_it.next();
2183
2184 for (Address rset_addr = p->RSetStart();
2185 rset_addr < p->RSetEnd();
2186 rset_addr += kIntSize) {
2187 int rset = Memory::int_at(rset_addr);
2188 if (rset != 0) {
2189 // Bits were set
2190 int intoff = rset_addr - p->address();
2191 int bitoff = 0;
2192 for (; bitoff < kBitsPerInt; ++bitoff) {
2193 if ((rset & (1 << bitoff)) != 0) {
2194 int bitpos = intoff*kBitsPerByte + bitoff;
2195 Address slot = p->OffsetToAddress(bitpos << kObjectAlignmentBits);
2196 Object** obj = reinterpret_cast<Object**>(slot);
2197 rset_marked_pointers++;
2198 if (Heap::InNewSpace(*obj))
2199 cross_gen_pointers++;
2200 }
2201 }
2202 }
2203 }
2204 }
2205
2206 pct = rset_marked_pointers == 0 ?
2207 0 : cross_gen_pointers * 100 / rset_marked_pointers;
2208 PrintF(" rset-marked pointers %d, to-new-space %d (%%%d)\n",
2209 rset_marked_pointers, cross_gen_pointers, pct);
2210
2211 ClearHistograms();
2212 HeapObjectIterator obj_it(this);
2213 while (obj_it.has_next()) { CollectHistogramInfo(obj_it.next()); }
2214 ReportHistogram(false);
2215}
2216
2217
2218void MapSpace::PrintRSet() { DoPrintRSet("map"); }
2219#endif
2220
2221
2222// -----------------------------------------------------------------------------
2223// LargeObjectIterator
2224
2225LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space) {
2226 current_ = space->first_chunk_;
2227 size_func_ = NULL;
2228}
2229
2230
2231LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space,
2232 HeapObjectCallback size_func) {
2233 current_ = space->first_chunk_;
2234 size_func_ = size_func;
2235}
2236
2237
2238HeapObject* LargeObjectIterator::next() {
2239 ASSERT(has_next());
2240 HeapObject* object = current_->GetObject();
2241 current_ = current_->next();
2242 return object;
2243}
2244
2245
2246// -----------------------------------------------------------------------------
2247// LargeObjectChunk
2248
2249LargeObjectChunk* LargeObjectChunk::New(int size_in_bytes,
kasper.lund7276f142008-07-30 08:49:36 +00002250 size_t* chunk_size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002251 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002252 size_t requested = ChunkSizeFor(size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002253 void* mem = MemoryAllocator::AllocateRawMemory(requested,
2254 chunk_size,
2255 executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002256 if (mem == NULL) return NULL;
2257 LOG(NewEvent("LargeObjectChunk", mem, *chunk_size));
2258 if (*chunk_size < requested) {
2259 MemoryAllocator::FreeRawMemory(mem, *chunk_size);
2260 LOG(DeleteEvent("LargeObjectChunk", mem));
2261 return NULL;
2262 }
2263 return reinterpret_cast<LargeObjectChunk*>(mem);
2264}
2265
2266
2267int LargeObjectChunk::ChunkSizeFor(int size_in_bytes) {
2268 int os_alignment = OS::AllocateAlignment();
2269 if (os_alignment < Page::kPageSize)
2270 size_in_bytes += (Page::kPageSize - os_alignment);
2271 return size_in_bytes + Page::kObjectStartOffset;
2272}
2273
2274// -----------------------------------------------------------------------------
2275// LargeObjectSpace
2276
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002277LargeObjectSpace::LargeObjectSpace(AllocationSpace id)
2278 : Space(id, NOT_EXECUTABLE), // Managed on a per-allocation basis
kasper.lund7276f142008-07-30 08:49:36 +00002279 first_chunk_(NULL),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002280 size_(0),
2281 page_count_(0) {}
2282
2283
2284bool LargeObjectSpace::Setup() {
2285 first_chunk_ = NULL;
2286 size_ = 0;
2287 page_count_ = 0;
2288 return true;
2289}
2290
2291
2292void LargeObjectSpace::TearDown() {
2293 while (first_chunk_ != NULL) {
2294 LargeObjectChunk* chunk = first_chunk_;
2295 first_chunk_ = first_chunk_->next();
2296 LOG(DeleteEvent("LargeObjectChunk", chunk->address()));
2297 MemoryAllocator::FreeRawMemory(chunk->address(), chunk->size());
2298 }
2299
2300 size_ = 0;
2301 page_count_ = 0;
2302}
2303
2304
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00002305#ifdef ENABLE_HEAP_PROTECTION
2306
2307void LargeObjectSpace::Protect() {
2308 LargeObjectChunk* chunk = first_chunk_;
2309 while (chunk != NULL) {
2310 MemoryAllocator::Protect(chunk->address(), chunk->size());
2311 chunk = chunk->next();
2312 }
2313}
2314
2315
2316void LargeObjectSpace::Unprotect() {
2317 LargeObjectChunk* chunk = first_chunk_;
2318 while (chunk != NULL) {
2319 bool is_code = chunk->GetObject()->IsCode();
2320 MemoryAllocator::Unprotect(chunk->address(), chunk->size(),
2321 is_code ? EXECUTABLE : NOT_EXECUTABLE);
2322 chunk = chunk->next();
2323 }
2324}
2325
2326#endif
2327
2328
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002329Object* LargeObjectSpace::AllocateRawInternal(int requested_size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002330 int object_size,
2331 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002332 ASSERT(0 < object_size && object_size <= requested_size);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002333
2334 // Check if we want to force a GC before growing the old space further.
2335 // If so, fail the allocation.
2336 if (!Heap::always_allocate() && Heap::OldGenerationAllocationLimitReached()) {
2337 return Failure::RetryAfterGC(requested_size, identity());
2338 }
2339
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002340 size_t chunk_size;
2341 LargeObjectChunk* chunk =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002342 LargeObjectChunk::New(requested_size, &chunk_size, executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002343 if (chunk == NULL) {
kasper.lund7276f142008-07-30 08:49:36 +00002344 return Failure::RetryAfterGC(requested_size, identity());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002345 }
2346
2347 size_ += chunk_size;
2348 page_count_++;
2349 chunk->set_next(first_chunk_);
2350 chunk->set_size(chunk_size);
2351 first_chunk_ = chunk;
2352
2353 // Set the object address and size in the page header and clear its
2354 // remembered set.
2355 Page* page = Page::FromAddress(RoundUp(chunk->address(), Page::kPageSize));
2356 Address object_address = page->ObjectAreaStart();
2357 // Clear the low order bit of the second word in the page to flag it as a
2358 // large object page. If the chunk_size happened to be written there, its
2359 // low order bit should already be clear.
2360 ASSERT((chunk_size & 0x1) == 0);
2361 page->is_normal_page &= ~0x1;
2362 page->ClearRSet();
2363 int extra_bytes = requested_size - object_size;
2364 if (extra_bytes > 0) {
2365 // The extra memory for the remembered set should be cleared.
2366 memset(object_address + object_size, 0, extra_bytes);
2367 }
2368
2369 return HeapObject::FromAddress(object_address);
2370}
2371
2372
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002373Object* LargeObjectSpace::AllocateRawCode(int size_in_bytes) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002374 ASSERT(0 < size_in_bytes);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002375 return AllocateRawInternal(size_in_bytes,
2376 size_in_bytes,
2377 EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002378}
2379
2380
2381Object* LargeObjectSpace::AllocateRawFixedArray(int size_in_bytes) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002382 ASSERT(0 < size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002383 int extra_rset_bytes = ExtraRSetBytesFor(size_in_bytes);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002384 return AllocateRawInternal(size_in_bytes + extra_rset_bytes,
2385 size_in_bytes,
2386 NOT_EXECUTABLE);
2387}
2388
2389
2390Object* LargeObjectSpace::AllocateRaw(int size_in_bytes) {
2391 ASSERT(0 < size_in_bytes);
2392 return AllocateRawInternal(size_in_bytes,
2393 size_in_bytes,
2394 NOT_EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002395}
2396
2397
2398// GC support
2399Object* LargeObjectSpace::FindObject(Address a) {
2400 for (LargeObjectChunk* chunk = first_chunk_;
2401 chunk != NULL;
2402 chunk = chunk->next()) {
2403 Address chunk_address = chunk->address();
2404 if (chunk_address <= a && a < chunk_address + chunk->size()) {
2405 return chunk->GetObject();
2406 }
2407 }
2408 return Failure::Exception();
2409}
2410
2411
2412void LargeObjectSpace::ClearRSet() {
2413 ASSERT(Page::is_rset_in_use());
2414
2415 LargeObjectIterator it(this);
2416 while (it.has_next()) {
2417 HeapObject* object = it.next();
2418 // We only have code, sequential strings, or fixed arrays in large
2419 // object space, and only fixed arrays need remembered set support.
2420 if (object->IsFixedArray()) {
2421 // Clear the normal remembered set region of the page;
2422 Page* page = Page::FromAddress(object->address());
2423 page->ClearRSet();
2424
2425 // Clear the extra remembered set.
2426 int size = object->Size();
2427 int extra_rset_bytes = ExtraRSetBytesFor(size);
2428 memset(object->address() + size, 0, extra_rset_bytes);
2429 }
2430 }
2431}
2432
2433
2434void LargeObjectSpace::IterateRSet(ObjectSlotCallback copy_object_func) {
2435 ASSERT(Page::is_rset_in_use());
2436
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002437 static void* lo_rset_histogram = StatsTable::CreateHistogram(
2438 "V8.RSetLO",
2439 0,
2440 // Keeping this histogram's buckets the same as the paged space histogram.
2441 Page::kObjectAreaSize / kPointerSize,
2442 30);
2443
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002444 LargeObjectIterator it(this);
2445 while (it.has_next()) {
2446 // We only have code, sequential strings, or fixed arrays in large
2447 // object space, and only fixed arrays can possibly contain pointers to
2448 // the young generation.
2449 HeapObject* object = it.next();
2450 if (object->IsFixedArray()) {
2451 // Iterate the normal page remembered set range.
2452 Page* page = Page::FromAddress(object->address());
2453 Address object_end = object->address() + object->Size();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002454 int count = Heap::IterateRSetRange(page->ObjectAreaStart(),
2455 Min(page->ObjectAreaEnd(), object_end),
2456 page->RSetStart(),
2457 copy_object_func);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002458
2459 // Iterate the extra array elements.
2460 if (object_end > page->ObjectAreaEnd()) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002461 count += Heap::IterateRSetRange(page->ObjectAreaEnd(), object_end,
2462 object_end, copy_object_func);
2463 }
2464 if (lo_rset_histogram != NULL) {
2465 StatsTable::AddHistogramSample(lo_rset_histogram, count);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002466 }
2467 }
2468 }
2469}
2470
2471
2472void LargeObjectSpace::FreeUnmarkedObjects() {
2473 LargeObjectChunk* previous = NULL;
2474 LargeObjectChunk* current = first_chunk_;
2475 while (current != NULL) {
2476 HeapObject* object = current->GetObject();
kasper.lund7276f142008-07-30 08:49:36 +00002477 if (object->IsMarked()) {
2478 object->ClearMark();
2479 MarkCompactCollector::tracer()->decrement_marked_count();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002480 previous = current;
2481 current = current->next();
2482 } else {
2483 Address chunk_address = current->address();
2484 size_t chunk_size = current->size();
2485
2486 // Cut the chunk out from the chunk list.
2487 current = current->next();
2488 if (previous == NULL) {
2489 first_chunk_ = current;
2490 } else {
2491 previous->set_next(current);
2492 }
2493
2494 // Free the chunk.
2495 if (object->IsCode()) {
2496 LOG(CodeDeleteEvent(object->address()));
2497 }
2498 size_ -= chunk_size;
2499 page_count_--;
2500 MemoryAllocator::FreeRawMemory(chunk_address, chunk_size);
2501 LOG(DeleteEvent("LargeObjectChunk", chunk_address));
2502 }
2503 }
2504}
2505
2506
2507bool LargeObjectSpace::Contains(HeapObject* object) {
2508 Address address = object->address();
2509 Page* page = Page::FromAddress(address);
2510
2511 SLOW_ASSERT(!page->IsLargeObjectPage()
2512 || !FindObject(address)->IsFailure());
2513
2514 return page->IsLargeObjectPage();
2515}
2516
2517
2518#ifdef DEBUG
2519// We do not assume that the large object iterator works, because it depends
2520// on the invariants we are checking during verification.
2521void LargeObjectSpace::Verify() {
2522 for (LargeObjectChunk* chunk = first_chunk_;
2523 chunk != NULL;
2524 chunk = chunk->next()) {
2525 // Each chunk contains an object that starts at the large object page's
2526 // object area start.
2527 HeapObject* object = chunk->GetObject();
2528 Page* page = Page::FromAddress(object->address());
2529 ASSERT(object->address() == page->ObjectAreaStart());
2530
2531 // The first word should be a map, and we expect all map pointers to be
2532 // in map space.
2533 Map* map = object->map();
2534 ASSERT(map->IsMap());
2535 ASSERT(Heap::map_space()->Contains(map));
2536
2537 // We have only code, sequential strings, fixed arrays, and byte arrays
2538 // in large object space.
2539 ASSERT(object->IsCode() || object->IsSeqString()
2540 || object->IsFixedArray() || object->IsByteArray());
2541
2542 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002543 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002544
2545 // Byte arrays and strings don't have interior pointers.
2546 if (object->IsCode()) {
2547 VerifyPointersVisitor code_visitor;
2548 Code::cast(object)->ConvertICTargetsFromAddressToObject();
2549 object->IterateBody(map->instance_type(),
2550 object->Size(),
2551 &code_visitor);
2552 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
2553 } else if (object->IsFixedArray()) {
2554 // We loop over fixed arrays ourselves, rather then using the visitor,
2555 // because the visitor doesn't support the start/offset iteration
2556 // needed for IsRSetSet.
2557 FixedArray* array = FixedArray::cast(object);
2558 for (int j = 0; j < array->length(); j++) {
2559 Object* element = array->get(j);
2560 if (element->IsHeapObject()) {
2561 HeapObject* element_object = HeapObject::cast(element);
2562 ASSERT(Heap::Contains(element_object));
2563 ASSERT(element_object->map()->IsMap());
2564 if (Heap::InNewSpace(element_object)) {
2565 ASSERT(Page::IsRSetSet(object->address(),
2566 FixedArray::kHeaderSize + j * kPointerSize));
2567 }
2568 }
2569 }
2570 }
2571 }
2572}
2573
2574
2575void LargeObjectSpace::Print() {
2576 LargeObjectIterator it(this);
2577 while (it.has_next()) {
2578 it.next()->Print();
2579 }
2580}
2581
2582
2583void LargeObjectSpace::ReportStatistics() {
2584 PrintF(" size: %d\n", size_);
2585 int num_objects = 0;
2586 ClearHistograms();
2587 LargeObjectIterator it(this);
2588 while (it.has_next()) {
2589 num_objects++;
2590 CollectHistogramInfo(it.next());
2591 }
2592
2593 PrintF(" number of objects %d\n", num_objects);
2594 if (num_objects > 0) ReportHistogram(false);
2595}
2596
2597
2598void LargeObjectSpace::CollectCodeStatistics() {
2599 LargeObjectIterator obj_it(this);
2600 while (obj_it.has_next()) {
2601 HeapObject* obj = obj_it.next();
2602 if (obj->IsCode()) {
2603 Code* code = Code::cast(obj);
2604 code_kind_statistics[code->kind()] += code->Size();
2605 }
2606 }
2607}
2608
2609
2610void LargeObjectSpace::PrintRSet() {
2611 LargeObjectIterator it(this);
2612 while (it.has_next()) {
2613 HeapObject* object = it.next();
2614 if (object->IsFixedArray()) {
2615 Page* page = Page::FromAddress(object->address());
2616
2617 Address allocation_top = object->address() + object->Size();
2618 PrintF("large page 0x%x:\n", page);
2619 PrintRSetRange(page->RSetStart(), page->RSetEnd(),
2620 reinterpret_cast<Object**>(object->address()),
2621 allocation_top);
2622 int extra_array_bytes = object->Size() - Page::kObjectAreaSize;
2623 int extra_rset_bits = RoundUp(extra_array_bytes / kPointerSize,
2624 kBitsPerInt);
2625 PrintF("------------------------------------------------------------"
2626 "-----------\n");
2627 PrintRSetRange(allocation_top,
2628 allocation_top + extra_rset_bits / kBitsPerByte,
2629 reinterpret_cast<Object**>(object->address()
2630 + Page::kObjectAreaSize),
2631 allocation_top);
2632 PrintF("\n");
2633 }
2634 }
2635}
2636#endif // DEBUG
2637
2638} } // namespace v8::internal