blob: 0c10d2c77952a9bd8ad8875883858b62dcadb578 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
2// 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#ifndef V8_SPACES_H_
29#define V8_SPACES_H_
30
31#include "list-inl.h"
32#include "log.h"
33
34namespace v8 {
35namespace internal {
36
37// -----------------------------------------------------------------------------
38// Heap structures:
39//
40// A JS heap consists of a young generation, an old generation, and a large
41// object space. The young generation is divided into two semispaces. A
42// scavenger implements Cheney's copying algorithm. The old generation is
43// separated into a map space and an old object space. The map space contains
44// all (and only) map objects, the rest of old objects go into the old space.
45// The old generation is collected by a mark-sweep-compact collector.
46//
47// The semispaces of the young generation are contiguous. The old and map
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010048// spaces consists of a list of pages. A page has a page header and an object
49// area. A page size is deliberately chosen as 8K bytes.
50// The first word of a page is an opaque page header that has the
Steve Blocka7e24c12009-10-30 11:49:00 +000051// address of the next page and its ownership information. The second word may
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010052// have the allocation top address of this page. Heap objects are aligned to the
53// pointer size.
Steve Blocka7e24c12009-10-30 11:49:00 +000054//
55// There is a separate large object space for objects larger than
56// Page::kMaxHeapObjectSize, so that they do not have to move during
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010057// collection. The large object space is paged. Pages in large object space
58// may be larger than 8K.
Steve Blocka7e24c12009-10-30 11:49:00 +000059//
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010060// A card marking write barrier is used to keep track of intergenerational
61// references. Old space pages are divided into regions of Page::kRegionSize
62// size. Each region has a corresponding dirty bit in the page header which is
63// set if the region might contain pointers to new space. For details about
64// dirty bits encoding see comments in the Page::GetRegionNumberForAddress()
65// method body.
66//
67// During scavenges and mark-sweep collections we iterate intergenerational
68// pointers without decoding heap object maps so if the page belongs to old
69// pointer space or large object space it is essential to guarantee that
70// the page does not contain any garbage pointers to new space: every pointer
71// aligned word which satisfies the Heap::InNewSpace() predicate must be a
72// pointer to a live heap object in new space. Thus objects in old pointer
73// and large object spaces should have a special layout (e.g. no bare integer
74// fields). This requirement does not apply to map space which is iterated in
75// a special fashion. However we still require pointer fields of dead maps to
76// be cleaned.
77//
78// To enable lazy cleaning of old space pages we use a notion of allocation
79// watermark. Every pointer under watermark is considered to be well formed.
80// Page allocation watermark is not necessarily equal to page allocation top but
81// all alive objects on page should reside under allocation watermark.
82// During scavenge allocation watermark might be bumped and invalid pointers
83// might appear below it. To avoid following them we store a valid watermark
84// into special field in the page header and set a page WATERMARK_INVALIDATED
85// flag. For details see comments in the Page::SetAllocationWatermark() method
86// body.
87//
Steve Blocka7e24c12009-10-30 11:49:00 +000088
89// Some assertion macros used in the debugging mode.
90
Leon Clarkee46be812010-01-19 14:06:41 +000091#define ASSERT_PAGE_ALIGNED(address) \
Steve Blocka7e24c12009-10-30 11:49:00 +000092 ASSERT((OffsetFrom(address) & Page::kPageAlignmentMask) == 0)
93
Leon Clarkee46be812010-01-19 14:06:41 +000094#define ASSERT_OBJECT_ALIGNED(address) \
Steve Blocka7e24c12009-10-30 11:49:00 +000095 ASSERT((OffsetFrom(address) & kObjectAlignmentMask) == 0)
96
Leon Clarkee46be812010-01-19 14:06:41 +000097#define ASSERT_MAP_ALIGNED(address) \
98 ASSERT((OffsetFrom(address) & kMapAlignmentMask) == 0)
99
100#define ASSERT_OBJECT_SIZE(size) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000101 ASSERT((0 < size) && (size <= Page::kMaxHeapObjectSize))
102
Leon Clarkee46be812010-01-19 14:06:41 +0000103#define ASSERT_PAGE_OFFSET(offset) \
104 ASSERT((Page::kObjectStartOffset <= offset) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000105 && (offset <= Page::kPageSize))
106
Leon Clarkee46be812010-01-19 14:06:41 +0000107#define ASSERT_MAP_PAGE_INDEX(index) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000108 ASSERT((0 <= index) && (index <= MapSpace::kMaxMapPageIndex))
109
110
111class PagedSpace;
112class MemoryAllocator;
113class AllocationInfo;
114
115// -----------------------------------------------------------------------------
116// A page normally has 8K bytes. Large object pages may be larger. A page
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100117// address is always aligned to the 8K page size.
Steve Blocka7e24c12009-10-30 11:49:00 +0000118//
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100119// Each page starts with a header of Page::kPageHeaderSize size which contains
120// bookkeeping data.
Steve Blocka7e24c12009-10-30 11:49:00 +0000121//
122// The mark-compact collector transforms a map pointer into a page index and a
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100123// page offset. The exact encoding is described in the comments for
Leon Clarkee46be812010-01-19 14:06:41 +0000124// class MapWord in objects.h.
Steve Blocka7e24c12009-10-30 11:49:00 +0000125//
126// The only way to get a page pointer is by calling factory methods:
127// Page* p = Page::FromAddress(addr); or
128// Page* p = Page::FromAllocationTop(top);
129class Page {
130 public:
131 // Returns the page containing a given address. The address ranges
132 // from [page_addr .. page_addr + kPageSize[
133 //
134 // Note that this function only works for addresses in normal paged
135 // spaces and addresses in the first 8K of large object pages (i.e.,
136 // the start of large objects but not necessarily derived pointers
137 // within them).
138 INLINE(static Page* FromAddress(Address a)) {
139 return reinterpret_cast<Page*>(OffsetFrom(a) & ~kPageAlignmentMask);
140 }
141
142 // Returns the page containing an allocation top. Because an allocation
143 // top address can be the upper bound of the page, we need to subtract
144 // it with kPointerSize first. The address ranges from
145 // [page_addr + kObjectStartOffset .. page_addr + kPageSize].
146 INLINE(static Page* FromAllocationTop(Address top)) {
147 Page* p = FromAddress(top - kPointerSize);
148 ASSERT_PAGE_OFFSET(p->Offset(top));
149 return p;
150 }
151
152 // Returns the start address of this page.
153 Address address() { return reinterpret_cast<Address>(this); }
154
155 // Checks whether this is a valid page address.
156 bool is_valid() { return address() != NULL; }
157
158 // Returns the next page of this page.
159 inline Page* next_page();
160
161 // Return the end of allocation in this page. Undefined for unused pages.
162 inline Address AllocationTop();
163
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100164 // Return the allocation watermark for the page.
165 // For old space pages it is guaranteed that the area under the watermark
166 // does not contain any garbage pointers to new space.
167 inline Address AllocationWatermark();
168
169 // Return the allocation watermark offset from the beginning of the page.
170 inline uint32_t AllocationWatermarkOffset();
171
172 inline void SetAllocationWatermark(Address allocation_watermark);
173
174 inline void SetCachedAllocationWatermark(Address allocation_watermark);
175 inline Address CachedAllocationWatermark();
176
Steve Blocka7e24c12009-10-30 11:49:00 +0000177 // Returns the start address of the object area in this page.
178 Address ObjectAreaStart() { return address() + kObjectStartOffset; }
179
180 // Returns the end address (exclusive) of the object area in this page.
181 Address ObjectAreaEnd() { return address() + Page::kPageSize; }
182
Steve Blocka7e24c12009-10-30 11:49:00 +0000183 // Checks whether an address is page aligned.
184 static bool IsAlignedToPageSize(Address a) {
185 return 0 == (OffsetFrom(a) & kPageAlignmentMask);
186 }
187
Steve Block6ded16b2010-05-10 14:33:55 +0100188 // True if this page was in use before current compaction started.
189 // Result is valid only for pages owned by paged spaces and
190 // only after PagedSpace::PrepareForMarkCompact was called.
191 inline bool WasInUseBeforeMC();
192
193 inline void SetWasInUseBeforeMC(bool was_in_use);
194
Steve Blocka7e24c12009-10-30 11:49:00 +0000195 // True if this page is a large object page.
Steve Block6ded16b2010-05-10 14:33:55 +0100196 inline bool IsLargeObjectPage();
197
198 inline void SetIsLargeObjectPage(bool is_large_object_page);
Steve Blocka7e24c12009-10-30 11:49:00 +0000199
Steve Block791712a2010-08-27 10:21:07 +0100200 inline bool IsPageExecutable();
201
202 inline void SetIsPageExecutable(bool is_page_executable);
203
Steve Blocka7e24c12009-10-30 11:49:00 +0000204 // Returns the offset of a given address to this page.
205 INLINE(int Offset(Address a)) {
Steve Blockd0582a62009-12-15 09:54:21 +0000206 int offset = static_cast<int>(a - address());
Steve Blocka7e24c12009-10-30 11:49:00 +0000207 ASSERT_PAGE_OFFSET(offset);
208 return offset;
209 }
210
211 // Returns the address for a given offset to the this page.
212 Address OffsetToAddress(int offset) {
213 ASSERT_PAGE_OFFSET(offset);
214 return address() + offset;
215 }
216
217 // ---------------------------------------------------------------------
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100218 // Card marking support
Steve Blocka7e24c12009-10-30 11:49:00 +0000219
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100220 static const uint32_t kAllRegionsCleanMarks = 0x0;
221 static const uint32_t kAllRegionsDirtyMarks = 0xFFFFFFFF;
Steve Blocka7e24c12009-10-30 11:49:00 +0000222
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100223 inline uint32_t GetRegionMarks();
224 inline void SetRegionMarks(uint32_t dirty);
Steve Blocka7e24c12009-10-30 11:49:00 +0000225
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100226 inline uint32_t GetRegionMaskForAddress(Address addr);
227 inline uint32_t GetRegionMaskForSpan(Address start, int length_in_bytes);
228 inline int GetRegionNumberForAddress(Address addr);
Steve Blocka7e24c12009-10-30 11:49:00 +0000229
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100230 inline void MarkRegionDirty(Address addr);
231 inline bool IsRegionDirty(Address addr);
Steve Blocka7e24c12009-10-30 11:49:00 +0000232
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100233 inline void ClearRegionMarks(Address start,
234 Address end,
235 bool reaches_limit);
Steve Blocka7e24c12009-10-30 11:49:00 +0000236
Steve Blocka7e24c12009-10-30 11:49:00 +0000237 // Page size in bytes. This must be a multiple of the OS page size.
238 static const int kPageSize = 1 << kPageSizeBits;
239
240 // Page size mask.
241 static const intptr_t kPageAlignmentMask = (1 << kPageSizeBits) - 1;
242
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100243 static const int kPageHeaderSize = kPointerSize + kPointerSize + kIntSize +
244 kIntSize + kPointerSize;
Steve Blocka7e24c12009-10-30 11:49:00 +0000245
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100246 // The start offset of the object area in a page. Aligned to both maps and
247 // code alignment to be suitable for both.
248 static const int kObjectStartOffset =
249 CODE_POINTER_ALIGN(MAP_POINTER_ALIGN(kPageHeaderSize));
Steve Blocka7e24c12009-10-30 11:49:00 +0000250
251 // Object area size in bytes.
252 static const int kObjectAreaSize = kPageSize - kObjectStartOffset;
253
254 // Maximum object size that fits in a page.
255 static const int kMaxHeapObjectSize = kObjectAreaSize;
256
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100257 static const int kDirtyFlagOffset = 2 * kPointerSize;
258 static const int kRegionSizeLog2 = 8;
259 static const int kRegionSize = 1 << kRegionSizeLog2;
260 static const intptr_t kRegionAlignmentMask = (kRegionSize - 1);
261
262 STATIC_CHECK(kRegionSize == kPageSize / kBitsPerInt);
263
Steve Block6ded16b2010-05-10 14:33:55 +0100264 enum PageFlag {
Steve Block791712a2010-08-27 10:21:07 +0100265 IS_NORMAL_PAGE = 0,
266 WAS_IN_USE_BEFORE_MC,
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100267
268 // Page allocation watermark was bumped by preallocation during scavenge.
269 // Correct watermark can be retrieved by CachedAllocationWatermark() method
Steve Block791712a2010-08-27 10:21:07 +0100270 WATERMARK_INVALIDATED,
271 IS_EXECUTABLE,
272 NUM_PAGE_FLAGS // Must be last
Steve Block6ded16b2010-05-10 14:33:55 +0100273 };
Steve Block791712a2010-08-27 10:21:07 +0100274 static const int kPageFlagMask = (1 << NUM_PAGE_FLAGS) - 1;
Steve Block6ded16b2010-05-10 14:33:55 +0100275
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100276 // To avoid an additional WATERMARK_INVALIDATED flag clearing pass during
277 // scavenge we just invalidate the watermark on each old space page after
278 // processing it. And then we flip the meaning of the WATERMARK_INVALIDATED
279 // flag at the beginning of the next scavenge and each page becomes marked as
280 // having a valid watermark.
281 //
282 // The following invariant must hold for pages in old pointer and map spaces:
283 // If page is in use then page is marked as having invalid watermark at
284 // the beginning and at the end of any GC.
285 //
286 // This invariant guarantees that after flipping flag meaning at the
287 // beginning of scavenge all pages in use will be marked as having valid
288 // watermark.
289 static inline void FlipMeaningOfInvalidatedWatermarkFlag();
290
291 // Returns true if the page allocation watermark was not altered during
292 // scavenge.
293 inline bool IsWatermarkValid();
294
295 inline void InvalidateWatermark(bool value);
296
Steve Block6ded16b2010-05-10 14:33:55 +0100297 inline bool GetPageFlag(PageFlag flag);
298 inline void SetPageFlag(PageFlag flag, bool value);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100299 inline void ClearPageFlags();
300
301 inline void ClearGCFields();
302
Steve Block791712a2010-08-27 10:21:07 +0100303 static const int kAllocationWatermarkOffsetShift = WATERMARK_INVALIDATED + 1;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100304 static const int kAllocationWatermarkOffsetBits = kPageSizeBits + 1;
305 static const uint32_t kAllocationWatermarkOffsetMask =
306 ((1 << kAllocationWatermarkOffsetBits) - 1) <<
307 kAllocationWatermarkOffsetShift;
308
309 static const uint32_t kFlagsMask =
310 ((1 << kAllocationWatermarkOffsetShift) - 1);
311
312 STATIC_CHECK(kBitsPerInt - kAllocationWatermarkOffsetShift >=
313 kAllocationWatermarkOffsetBits);
314
315 // This field contains the meaning of the WATERMARK_INVALIDATED flag.
316 // Instead of clearing this flag from all pages we just flip
317 // its meaning at the beginning of a scavenge.
318 static intptr_t watermark_invalidated_mark_;
Steve Block6ded16b2010-05-10 14:33:55 +0100319
Steve Blocka7e24c12009-10-30 11:49:00 +0000320 //---------------------------------------------------------------------------
321 // Page header description.
322 //
323 // If a page is not in the large object space, the first word,
324 // opaque_header, encodes the next page address (aligned to kPageSize 8K)
325 // and the chunk number (0 ~ 8K-1). Only MemoryAllocator should use
326 // opaque_header. The value range of the opaque_header is [0..kPageSize[,
327 // or [next_page_start, next_page_end[. It cannot point to a valid address
328 // in the current page. If a page is in the large object space, the first
329 // word *may* (if the page start and large object chunk start are the
330 // same) contain the address of the next large object chunk.
331 intptr_t opaque_header;
332
333 // If the page is not in the large object space, the low-order bit of the
334 // second word is set. If the page is in the large object space, the
335 // second word *may* (if the page start and large object chunk start are
336 // the same) contain the large object chunk size. In either case, the
337 // low-order bit for large object pages will be cleared.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100338 // For normal pages this word is used to store page flags and
339 // offset of allocation top.
340 intptr_t flags_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000341
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100342 // This field contains dirty marks for regions covering the page. Only dirty
343 // regions might contain intergenerational references.
344 // Only 32 dirty marks are supported so for large object pages several regions
345 // might be mapped to a single dirty mark.
346 uint32_t dirty_regions_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000347
348 // The index of the page in its owner space.
349 int mc_page_index;
350
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100351 // During mark-compact collections this field contains the forwarding address
352 // of the first live object in this page.
353 // During scavenge collection this field is used to store allocation watermark
354 // if it is altered during scavenge.
Steve Blocka7e24c12009-10-30 11:49:00 +0000355 Address mc_first_forwarded;
Steve Blocka7e24c12009-10-30 11:49:00 +0000356};
357
358
359// ----------------------------------------------------------------------------
360// Space is the abstract superclass for all allocation spaces.
361class Space : public Malloced {
362 public:
363 Space(AllocationSpace id, Executability executable)
364 : id_(id), executable_(executable) {}
365
366 virtual ~Space() {}
367
368 // Does the space need executable memory?
369 Executability executable() { return executable_; }
370
371 // Identity used in error reporting.
372 AllocationSpace identity() { return id_; }
373
Ben Murdochf87a2032010-10-22 12:50:53 +0100374 virtual intptr_t Size() = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000375
Steve Block6ded16b2010-05-10 14:33:55 +0100376#ifdef ENABLE_HEAP_PROTECTION
377 // Protect/unprotect the space by marking it read-only/writable.
378 virtual void Protect() = 0;
379 virtual void Unprotect() = 0;
380#endif
381
Steve Blocka7e24c12009-10-30 11:49:00 +0000382#ifdef DEBUG
383 virtual void Print() = 0;
384#endif
385
Leon Clarkee46be812010-01-19 14:06:41 +0000386 // After calling this we can allocate a certain number of bytes using only
387 // linear allocation (with a LinearAllocationScope and an AlwaysAllocateScope)
388 // without using freelists or causing a GC. This is used by partial
389 // snapshots. It returns true of space was reserved or false if a GC is
390 // needed. For paged spaces the space requested must include the space wasted
391 // at the end of each when allocating linearly.
392 virtual bool ReserveSpace(int bytes) = 0;
393
Steve Blocka7e24c12009-10-30 11:49:00 +0000394 private:
395 AllocationSpace id_;
396 Executability executable_;
397};
398
399
400// ----------------------------------------------------------------------------
401// All heap objects containing executable code (code objects) must be allocated
402// from a 2 GB range of memory, so that they can call each other using 32-bit
403// displacements. This happens automatically on 32-bit platforms, where 32-bit
404// displacements cover the entire 4GB virtual address space. On 64-bit
405// platforms, we support this using the CodeRange object, which reserves and
406// manages a range of virtual memory.
407class CodeRange : public AllStatic {
408 public:
409 // Reserves a range of virtual memory, but does not commit any of it.
410 // Can only be called once, at heap initialization time.
411 // Returns false on failure.
412 static bool Setup(const size_t requested_size);
413
414 // Frees the range of virtual memory, and frees the data structures used to
415 // manage it.
416 static void TearDown();
417
418 static bool exists() { return code_range_ != NULL; }
419 static bool contains(Address address) {
420 if (code_range_ == NULL) return false;
421 Address start = static_cast<Address>(code_range_->address());
422 return start <= address && address < start + code_range_->size();
423 }
424
425 // Allocates a chunk of memory from the large-object portion of
426 // the code range. On platforms with no separate code range, should
427 // not be called.
John Reck59135872010-11-02 12:39:01 -0700428 MUST_USE_RESULT static void* AllocateRawMemory(const size_t requested,
429 size_t* allocated);
Steve Blocka7e24c12009-10-30 11:49:00 +0000430 static void FreeRawMemory(void* buf, size_t length);
431
432 private:
433 // The reserved range of virtual memory that all code objects are put in.
434 static VirtualMemory* code_range_;
435 // Plain old data class, just a struct plus a constructor.
436 class FreeBlock {
437 public:
438 FreeBlock(Address start_arg, size_t size_arg)
439 : start(start_arg), size(size_arg) {}
440 FreeBlock(void* start_arg, size_t size_arg)
441 : start(static_cast<Address>(start_arg)), size(size_arg) {}
442
443 Address start;
444 size_t size;
445 };
446
447 // Freed blocks of memory are added to the free list. When the allocation
448 // list is exhausted, the free list is sorted and merged to make the new
449 // allocation list.
450 static List<FreeBlock> free_list_;
451 // Memory is allocated from the free blocks on the allocation list.
452 // The block at current_allocation_block_index_ is the current block.
453 static List<FreeBlock> allocation_list_;
454 static int current_allocation_block_index_;
455
456 // Finds a block on the allocation list that contains at least the
457 // requested amount of memory. If none is found, sorts and merges
458 // the existing free memory blocks, and searches again.
459 // If none can be found, terminates V8 with FatalProcessOutOfMemory.
460 static void GetNextAllocationBlock(size_t requested);
461 // Compares the start addresses of two free blocks.
462 static int CompareFreeBlockAddress(const FreeBlock* left,
463 const FreeBlock* right);
464};
465
466
467// ----------------------------------------------------------------------------
468// A space acquires chunks of memory from the operating system. The memory
469// allocator manages chunks for the paged heap spaces (old space and map
470// space). A paged chunk consists of pages. Pages in a chunk have contiguous
471// addresses and are linked as a list.
472//
473// The allocator keeps an initial chunk which is used for the new space. The
474// leftover regions of the initial chunk are used for the initial chunks of
475// old space and map space if they are big enough to hold at least one page.
476// The allocator assumes that there is one old space and one map space, each
477// expands the space by allocating kPagesPerChunk pages except the last
478// expansion (before running out of space). The first chunk may contain fewer
479// than kPagesPerChunk pages as well.
480//
481// The memory allocator also allocates chunks for the large object space, but
482// they are managed by the space itself. The new space does not expand.
Steve Block6ded16b2010-05-10 14:33:55 +0100483//
484// The fact that pages for paged spaces are allocated and deallocated in chunks
485// induces a constraint on the order of pages in a linked lists. We say that
486// pages are linked in the chunk-order if and only if every two consecutive
487// pages from the same chunk are consecutive in the linked list.
488//
489
Steve Blocka7e24c12009-10-30 11:49:00 +0000490
491class MemoryAllocator : public AllStatic {
492 public:
493 // Initializes its internal bookkeeping structures.
Russell Brenner90bac252010-11-18 13:33:46 -0800494 // Max capacity of the total space and executable memory limit.
495 static bool Setup(intptr_t max_capacity, intptr_t capacity_executable);
Steve Blocka7e24c12009-10-30 11:49:00 +0000496
497 // Deletes valid chunks.
498 static void TearDown();
499
500 // Reserves an initial address range of virtual memory to be split between
501 // the two new space semispaces, the old space, and the map space. The
502 // memory is not yet committed or assigned to spaces and split into pages.
503 // The initial chunk is unmapped when the memory allocator is torn down.
504 // This function should only be called when there is not already a reserved
505 // initial chunk (initial_chunk_ should be NULL). It returns the start
506 // address of the initial chunk if successful, with the side effect of
507 // setting the initial chunk, or else NULL if unsuccessful and leaves the
508 // initial chunk NULL.
509 static void* ReserveInitialChunk(const size_t requested);
510
511 // Commits pages from an as-yet-unmanaged block of virtual memory into a
512 // paged space. The block should be part of the initial chunk reserved via
513 // a call to ReserveInitialChunk. The number of pages is always returned in
514 // the output parameter num_pages. This function assumes that the start
515 // address is non-null and that it is big enough to hold at least one
516 // page-aligned page. The call always succeeds, and num_pages is always
517 // greater than zero.
518 static Page* CommitPages(Address start, size_t size, PagedSpace* owner,
519 int* num_pages);
520
521 // Commit a contiguous block of memory from the initial chunk. Assumes that
522 // the address is not NULL, the size is greater than zero, and that the
523 // block is contained in the initial chunk. Returns true if it succeeded
524 // and false otherwise.
525 static bool CommitBlock(Address start, size_t size, Executability executable);
526
Steve Blocka7e24c12009-10-30 11:49:00 +0000527 // Uncommit a contiguous block of memory [start..(start+size)[.
528 // start is not NULL, the size is greater than zero, and the
529 // block is contained in the initial chunk. Returns true if it succeeded
530 // and false otherwise.
531 static bool UncommitBlock(Address start, size_t size);
532
Leon Clarke4515c472010-02-03 11:58:03 +0000533 // Zaps a contiguous block of memory [start..(start+size)[ thus
534 // filling it up with a recognizable non-NULL bit pattern.
535 static void ZapBlock(Address start, size_t size);
536
Steve Blocka7e24c12009-10-30 11:49:00 +0000537 // Attempts to allocate the requested (non-zero) number of pages from the
538 // OS. Fewer pages might be allocated than requested. If it fails to
539 // allocate memory for the OS or cannot allocate a single page, this
540 // function returns an invalid page pointer (NULL). The caller must check
541 // whether the returned page is valid (by calling Page::is_valid()). It is
542 // guaranteed that allocated pages have contiguous addresses. The actual
543 // number of allocated pages is returned in the output parameter
544 // allocated_pages. If the PagedSpace owner is executable and there is
545 // a code range, the pages are allocated from the code range.
546 static Page* AllocatePages(int requested_pages, int* allocated_pages,
547 PagedSpace* owner);
548
Steve Block6ded16b2010-05-10 14:33:55 +0100549 // Frees pages from a given page and after. Requires pages to be
550 // linked in chunk-order (see comment for class).
551 // If 'p' is the first page of a chunk, pages from 'p' are freed
552 // and this function returns an invalid page pointer.
553 // Otherwise, the function searches a page after 'p' that is
554 // the first page of a chunk. Pages after the found page
555 // are freed and the function returns 'p'.
Steve Blocka7e24c12009-10-30 11:49:00 +0000556 static Page* FreePages(Page* p);
557
Steve Block6ded16b2010-05-10 14:33:55 +0100558 // Frees all pages owned by given space.
559 static void FreeAllPages(PagedSpace* space);
560
Steve Blocka7e24c12009-10-30 11:49:00 +0000561 // Allocates and frees raw memory of certain size.
562 // These are just thin wrappers around OS::Allocate and OS::Free,
563 // but keep track of allocated bytes as part of heap.
564 // If the flag is EXECUTABLE and a code range exists, the requested
565 // memory is allocated from the code range. If a code range exists
566 // and the freed memory is in it, the code range manages the freed memory.
John Reck59135872010-11-02 12:39:01 -0700567 MUST_USE_RESULT static void* AllocateRawMemory(const size_t requested,
568 size_t* allocated,
569 Executability executable);
Steve Block791712a2010-08-27 10:21:07 +0100570 static void FreeRawMemory(void* buf,
571 size_t length,
572 Executability executable);
Iain Merrick9ac36c92010-09-13 15:29:50 +0100573 static void PerformAllocationCallback(ObjectSpace space,
574 AllocationAction action,
575 size_t size);
576
577 static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
578 ObjectSpace space,
579 AllocationAction action);
580 static void RemoveMemoryAllocationCallback(
581 MemoryAllocationCallback callback);
582 static bool MemoryAllocationCallbackRegistered(
583 MemoryAllocationCallback callback);
Steve Blocka7e24c12009-10-30 11:49:00 +0000584
585 // Returns the maximum available bytes of heaps.
Ben Murdochf87a2032010-10-22 12:50:53 +0100586 static intptr_t Available() {
587 return capacity_ < size_ ? 0 : capacity_ - size_;
588 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000589
590 // Returns allocated spaces in bytes.
Ben Murdochf87a2032010-10-22 12:50:53 +0100591 static intptr_t Size() { return size_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000592
Russell Brenner90bac252010-11-18 13:33:46 -0800593 // Returns the maximum available executable bytes of heaps.
594 static int AvailableExecutable() {
595 if (capacity_executable_ < size_executable_) return 0;
596 return capacity_executable_ - size_executable_;
597 }
598
Steve Block791712a2010-08-27 10:21:07 +0100599 // Returns allocated executable spaces in bytes.
Ben Murdochf87a2032010-10-22 12:50:53 +0100600 static intptr_t SizeExecutable() { return size_executable_; }
Steve Block791712a2010-08-27 10:21:07 +0100601
Steve Blocka7e24c12009-10-30 11:49:00 +0000602 // Returns maximum available bytes that the old space can have.
Ben Murdochf87a2032010-10-22 12:50:53 +0100603 static intptr_t MaxAvailable() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000604 return (Available() / Page::kPageSize) * Page::kObjectAreaSize;
605 }
606
607 // Links two pages.
608 static inline void SetNextPage(Page* prev, Page* next);
609
610 // Returns the next page of a given page.
611 static inline Page* GetNextPage(Page* p);
612
613 // Checks whether a page belongs to a space.
614 static inline bool IsPageInSpace(Page* p, PagedSpace* space);
615
616 // Returns the space that owns the given page.
617 static inline PagedSpace* PageOwner(Page* page);
618
619 // Finds the first/last page in the same chunk as a given page.
620 static Page* FindFirstPageInSameChunk(Page* p);
621 static Page* FindLastPageInSameChunk(Page* p);
622
Steve Block6ded16b2010-05-10 14:33:55 +0100623 // Relinks list of pages owned by space to make it chunk-ordered.
624 // Returns new first and last pages of space.
625 // Also returns last page in relinked list which has WasInUsedBeforeMC
626 // flag set.
627 static void RelinkPageListInChunkOrder(PagedSpace* space,
628 Page** first_page,
629 Page** last_page,
630 Page** last_page_in_use);
631
Steve Blocka7e24c12009-10-30 11:49:00 +0000632#ifdef ENABLE_HEAP_PROTECTION
633 // Protect/unprotect a block of memory by marking it read-only/writable.
634 static inline void Protect(Address start, size_t size);
635 static inline void Unprotect(Address start, size_t size,
636 Executability executable);
637
638 // Protect/unprotect a chunk given a page in the chunk.
639 static inline void ProtectChunkFromPage(Page* page);
640 static inline void UnprotectChunkFromPage(Page* page);
641#endif
642
643#ifdef DEBUG
644 // Reports statistic info of the space.
645 static void ReportStatistics();
646#endif
647
648 // Due to encoding limitation, we can only have 8K chunks.
Leon Clarkee46be812010-01-19 14:06:41 +0000649 static const int kMaxNofChunks = 1 << kPageSizeBits;
Steve Blocka7e24c12009-10-30 11:49:00 +0000650 // If a chunk has at least 16 pages, the maximum heap size is about
651 // 8K * 8K * 16 = 1G bytes.
652#ifdef V8_TARGET_ARCH_X64
653 static const int kPagesPerChunk = 32;
654#else
655 static const int kPagesPerChunk = 16;
656#endif
657 static const int kChunkSize = kPagesPerChunk * Page::kPageSize;
658
659 private:
660 // Maximum space size in bytes.
Ben Murdochf87a2032010-10-22 12:50:53 +0100661 static intptr_t capacity_;
Russell Brenner90bac252010-11-18 13:33:46 -0800662 // Maximum subset of capacity_ that can be executable
663 static intptr_t capacity_executable_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000664
665 // Allocated space size in bytes.
Ben Murdochf87a2032010-10-22 12:50:53 +0100666 static intptr_t size_;
Steve Block791712a2010-08-27 10:21:07 +0100667 // Allocated executable space size in bytes.
Ben Murdochf87a2032010-10-22 12:50:53 +0100668 static intptr_t size_executable_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000669
Iain Merrick9ac36c92010-09-13 15:29:50 +0100670 struct MemoryAllocationCallbackRegistration {
671 MemoryAllocationCallbackRegistration(MemoryAllocationCallback callback,
672 ObjectSpace space,
673 AllocationAction action)
674 : callback(callback), space(space), action(action) {
675 }
676 MemoryAllocationCallback callback;
677 ObjectSpace space;
678 AllocationAction action;
679 };
680 // A List of callback that are triggered when memory is allocated or free'd
681 static List<MemoryAllocationCallbackRegistration>
682 memory_allocation_callbacks_;
683
Steve Blocka7e24c12009-10-30 11:49:00 +0000684 // The initial chunk of virtual memory.
685 static VirtualMemory* initial_chunk_;
686
687 // Allocated chunk info: chunk start address, chunk size, and owning space.
688 class ChunkInfo BASE_EMBEDDED {
689 public:
Iain Merrick9ac36c92010-09-13 15:29:50 +0100690 ChunkInfo() : address_(NULL),
691 size_(0),
692 owner_(NULL),
693 executable_(NOT_EXECUTABLE) {}
694 inline void init(Address a, size_t s, PagedSpace* o);
Steve Blocka7e24c12009-10-30 11:49:00 +0000695 Address address() { return address_; }
696 size_t size() { return size_; }
697 PagedSpace* owner() { return owner_; }
Iain Merrick9ac36c92010-09-13 15:29:50 +0100698 // We save executability of the owner to allow using it
699 // when collecting stats after the owner has been destroyed.
700 Executability executable() const { return executable_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000701
702 private:
703 Address address_;
704 size_t size_;
705 PagedSpace* owner_;
Iain Merrick9ac36c92010-09-13 15:29:50 +0100706 Executability executable_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000707 };
708
709 // Chunks_, free_chunk_ids_ and top_ act as a stack of free chunk ids.
710 static List<ChunkInfo> chunks_;
711 static List<int> free_chunk_ids_;
712 static int max_nof_chunks_;
713 static int top_;
714
715 // Push/pop a free chunk id onto/from the stack.
716 static void Push(int free_chunk_id);
717 static int Pop();
718 static bool OutOfChunkIds() { return top_ == 0; }
719
720 // Frees a chunk.
721 static void DeleteChunk(int chunk_id);
722
723 // Basic check whether a chunk id is in the valid range.
724 static inline bool IsValidChunkId(int chunk_id);
725
726 // Checks whether a chunk id identifies an allocated chunk.
727 static inline bool IsValidChunk(int chunk_id);
728
729 // Returns the chunk id that a page belongs to.
730 static inline int GetChunkId(Page* p);
731
732 // True if the address lies in the initial chunk.
733 static inline bool InInitialChunk(Address address);
734
735 // Initializes pages in a chunk. Returns the first page address.
736 // This function and GetChunkId() are provided for the mark-compact
737 // collector to rebuild page headers in the from space, which is
738 // used as a marking stack and its page headers are destroyed.
739 static Page* InitializePagesInChunk(int chunk_id, int pages_in_chunk,
740 PagedSpace* owner);
Steve Block6ded16b2010-05-10 14:33:55 +0100741
742 static Page* RelinkPagesInChunk(int chunk_id,
743 Address chunk_start,
744 size_t chunk_size,
745 Page* prev,
746 Page** last_page_in_use);
Steve Blocka7e24c12009-10-30 11:49:00 +0000747};
748
749
750// -----------------------------------------------------------------------------
751// Interface for heap object iterator to be implemented by all object space
752// object iterators.
753//
Leon Clarked91b9f72010-01-27 17:25:45 +0000754// NOTE: The space specific object iterators also implements the own next()
755// method which is used to avoid using virtual functions
Steve Blocka7e24c12009-10-30 11:49:00 +0000756// iterating a specific space.
757
758class ObjectIterator : public Malloced {
759 public:
760 virtual ~ObjectIterator() { }
761
Steve Blocka7e24c12009-10-30 11:49:00 +0000762 virtual HeapObject* next_object() = 0;
763};
764
765
766// -----------------------------------------------------------------------------
767// Heap object iterator in new/old/map spaces.
768//
769// A HeapObjectIterator iterates objects from a given address to the
770// top of a space. The given address must be below the current
771// allocation pointer (space top). There are some caveats.
772//
773// (1) If the space top changes upward during iteration (because of
774// allocating new objects), the iterator does not iterate objects
775// above the original space top. The caller must create a new
776// iterator starting from the old top in order to visit these new
777// objects.
778//
779// (2) If new objects are allocated below the original allocation top
780// (e.g., free-list allocation in paged spaces), the new objects
781// may or may not be iterated depending on their position with
782// respect to the current point of iteration.
783//
784// (3) The space top should not change downward during iteration,
785// otherwise the iterator will return not-necessarily-valid
786// objects.
787
788class HeapObjectIterator: public ObjectIterator {
789 public:
790 // Creates a new object iterator in a given space. If a start
791 // address is not given, the iterator starts from the space bottom.
792 // If the size function is not given, the iterator calls the default
793 // Object::Size().
794 explicit HeapObjectIterator(PagedSpace* space);
795 HeapObjectIterator(PagedSpace* space, HeapObjectCallback size_func);
796 HeapObjectIterator(PagedSpace* space, Address start);
797 HeapObjectIterator(PagedSpace* space,
798 Address start,
799 HeapObjectCallback size_func);
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100800 HeapObjectIterator(Page* page, HeapObjectCallback size_func);
Steve Blocka7e24c12009-10-30 11:49:00 +0000801
Leon Clarked91b9f72010-01-27 17:25:45 +0000802 inline HeapObject* next() {
803 return (cur_addr_ < cur_limit_) ? FromCurrentPage() : FromNextPage();
804 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000805
806 // implementation of ObjectIterator.
Steve Blocka7e24c12009-10-30 11:49:00 +0000807 virtual HeapObject* next_object() { return next(); }
808
809 private:
810 Address cur_addr_; // current iteration point
811 Address end_addr_; // end iteration point
812 Address cur_limit_; // current page limit
813 HeapObjectCallback size_func_; // size function
814 Page* end_page_; // caches the page of the end address
815
Leon Clarked91b9f72010-01-27 17:25:45 +0000816 HeapObject* FromCurrentPage() {
817 ASSERT(cur_addr_ < cur_limit_);
818
819 HeapObject* obj = HeapObject::FromAddress(cur_addr_);
820 int obj_size = (size_func_ == NULL) ? obj->Size() : size_func_(obj);
821 ASSERT_OBJECT_SIZE(obj_size);
822
823 cur_addr_ += obj_size;
824 ASSERT(cur_addr_ <= cur_limit_);
825
826 return obj;
827 }
828
829 // Slow path of next, goes into the next page.
830 HeapObject* FromNextPage();
Steve Blocka7e24c12009-10-30 11:49:00 +0000831
832 // Initializes fields.
833 void Initialize(Address start, Address end, HeapObjectCallback size_func);
834
835#ifdef DEBUG
836 // Verifies whether fields have valid values.
837 void Verify();
838#endif
839};
840
841
842// -----------------------------------------------------------------------------
843// A PageIterator iterates the pages in a paged space.
844//
845// The PageIterator class provides three modes for iterating pages in a space:
846// PAGES_IN_USE iterates pages containing allocated objects.
847// PAGES_USED_BY_MC iterates pages that hold relocated objects during a
848// mark-compact collection.
849// ALL_PAGES iterates all pages in the space.
850//
851// There are some caveats.
852//
853// (1) If the space expands during iteration, new pages will not be
854// returned by the iterator in any mode.
855//
856// (2) If new objects are allocated during iteration, they will appear
857// in pages returned by the iterator. Allocation may cause the
858// allocation pointer or MC allocation pointer in the last page to
859// change between constructing the iterator and iterating the last
860// page.
861//
862// (3) The space should not shrink during iteration, otherwise the
863// iterator will return deallocated pages.
864
865class PageIterator BASE_EMBEDDED {
866 public:
867 enum Mode {
868 PAGES_IN_USE,
869 PAGES_USED_BY_MC,
870 ALL_PAGES
871 };
872
873 PageIterator(PagedSpace* space, Mode mode);
874
875 inline bool has_next();
876 inline Page* next();
877
878 private:
879 PagedSpace* space_;
880 Page* prev_page_; // Previous page returned.
881 Page* stop_page_; // Page to stop at (last page returned by the iterator).
882};
883
884
885// -----------------------------------------------------------------------------
886// A space has a list of pages. The next page can be accessed via
887// Page::next_page() call. The next page of the last page is an
888// invalid page pointer. A space can expand and shrink dynamically.
889
890// An abstraction of allocation and relocation pointers in a page-structured
891// space.
892class AllocationInfo {
893 public:
894 Address top; // current allocation top
895 Address limit; // current allocation limit
896
897#ifdef DEBUG
898 bool VerifyPagedAllocation() {
899 return (Page::FromAllocationTop(top) == Page::FromAllocationTop(limit))
900 && (top <= limit);
901 }
902#endif
903};
904
905
906// An abstraction of the accounting statistics of a page-structured space.
907// The 'capacity' of a space is the number of object-area bytes (ie, not
908// including page bookkeeping structures) currently in the space. The 'size'
909// of a space is the number of allocated bytes, the 'waste' in the space is
910// the number of bytes that are not allocated and not available to
911// allocation without reorganizing the space via a GC (eg, small blocks due
912// to internal fragmentation, top of page areas in map space), and the bytes
913// 'available' is the number of unallocated bytes that are not waste. The
914// capacity is the sum of size, waste, and available.
915//
916// The stats are only set by functions that ensure they stay balanced. These
917// functions increase or decrease one of the non-capacity stats in
918// conjunction with capacity, or else they always balance increases and
919// decreases to the non-capacity stats.
920class AllocationStats BASE_EMBEDDED {
921 public:
922 AllocationStats() { Clear(); }
923
924 // Zero out all the allocation statistics (ie, no capacity).
925 void Clear() {
926 capacity_ = 0;
927 available_ = 0;
928 size_ = 0;
929 waste_ = 0;
930 }
931
932 // Reset the allocation statistics (ie, available = capacity with no
933 // wasted or allocated bytes).
934 void Reset() {
935 available_ = capacity_;
936 size_ = 0;
937 waste_ = 0;
938 }
939
940 // Accessors for the allocation statistics.
Ben Murdochf87a2032010-10-22 12:50:53 +0100941 intptr_t Capacity() { return capacity_; }
942 intptr_t Available() { return available_; }
943 intptr_t Size() { return size_; }
944 intptr_t Waste() { return waste_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000945
946 // Grow the space by adding available bytes.
947 void ExpandSpace(int size_in_bytes) {
948 capacity_ += size_in_bytes;
949 available_ += size_in_bytes;
950 }
951
952 // Shrink the space by removing available bytes.
953 void ShrinkSpace(int size_in_bytes) {
954 capacity_ -= size_in_bytes;
955 available_ -= size_in_bytes;
956 }
957
958 // Allocate from available bytes (available -> size).
Ben Murdochf87a2032010-10-22 12:50:53 +0100959 void AllocateBytes(intptr_t size_in_bytes) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000960 available_ -= size_in_bytes;
961 size_ += size_in_bytes;
962 }
963
964 // Free allocated bytes, making them available (size -> available).
Ben Murdochf87a2032010-10-22 12:50:53 +0100965 void DeallocateBytes(intptr_t size_in_bytes) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000966 size_ -= size_in_bytes;
967 available_ += size_in_bytes;
968 }
969
970 // Waste free bytes (available -> waste).
971 void WasteBytes(int size_in_bytes) {
972 available_ -= size_in_bytes;
973 waste_ += size_in_bytes;
974 }
975
976 // Consider the wasted bytes to be allocated, as they contain filler
977 // objects (waste -> size).
Ben Murdochf87a2032010-10-22 12:50:53 +0100978 void FillWastedBytes(intptr_t size_in_bytes) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000979 waste_ -= size_in_bytes;
980 size_ += size_in_bytes;
981 }
982
983 private:
Ben Murdochf87a2032010-10-22 12:50:53 +0100984 intptr_t capacity_;
985 intptr_t available_;
986 intptr_t size_;
987 intptr_t waste_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000988};
989
990
991class PagedSpace : public Space {
992 public:
993 // Creates a space with a maximum capacity, and an id.
Ben Murdochf87a2032010-10-22 12:50:53 +0100994 PagedSpace(intptr_t max_capacity,
995 AllocationSpace id,
996 Executability executable);
Steve Blocka7e24c12009-10-30 11:49:00 +0000997
998 virtual ~PagedSpace() {}
999
1000 // Set up the space using the given address range of virtual memory (from
1001 // the memory allocator's initial chunk) if possible. If the block of
1002 // addresses is not big enough to contain a single page-aligned page, a
1003 // fresh chunk will be allocated.
1004 bool Setup(Address start, size_t size);
1005
1006 // Returns true if the space has been successfully set up and not
1007 // subsequently torn down.
1008 bool HasBeenSetup();
1009
1010 // Cleans up the space, frees all pages in this space except those belonging
1011 // to the initial chunk, uncommits addresses in the initial chunk.
1012 void TearDown();
1013
1014 // Checks whether an object/address is in this space.
1015 inline bool Contains(Address a);
1016 bool Contains(HeapObject* o) { return Contains(o->address()); }
1017
1018 // Given an address occupied by a live object, return that object if it is
1019 // in this space, or Failure::Exception() if it is not. The implementation
1020 // iterates over objects in the page containing the address, the cost is
1021 // linear in the number of objects in the page. It may be slow.
John Reck59135872010-11-02 12:39:01 -07001022 MUST_USE_RESULT MaybeObject* FindObject(Address addr);
Steve Blocka7e24c12009-10-30 11:49:00 +00001023
1024 // Checks whether page is currently in use by this space.
1025 bool IsUsed(Page* page);
1026
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001027 void MarkAllPagesClean();
Steve Blocka7e24c12009-10-30 11:49:00 +00001028
1029 // Prepares for a mark-compact GC.
Steve Block6ded16b2010-05-10 14:33:55 +01001030 virtual void PrepareForMarkCompact(bool will_compact);
Steve Blocka7e24c12009-10-30 11:49:00 +00001031
Steve Block6ded16b2010-05-10 14:33:55 +01001032 // The top of allocation in a page in this space. Undefined if page is unused.
1033 Address PageAllocationTop(Page* page) {
1034 return page == TopPageOf(allocation_info_) ? top()
1035 : PageAllocationLimit(page);
1036 }
1037
1038 // The limit of allocation for a page in this space.
1039 virtual Address PageAllocationLimit(Page* page) = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00001040
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001041 void FlushTopPageWatermark() {
1042 AllocationTopPage()->SetCachedAllocationWatermark(top());
1043 AllocationTopPage()->InvalidateWatermark(true);
1044 }
1045
Steve Blocka7e24c12009-10-30 11:49:00 +00001046 // Current capacity without growing (Size() + Available() + Waste()).
Ben Murdochf87a2032010-10-22 12:50:53 +01001047 intptr_t Capacity() { return accounting_stats_.Capacity(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001048
Steve Block3ce2e202009-11-05 08:53:23 +00001049 // Total amount of memory committed for this space. For paged
1050 // spaces this equals the capacity.
Ben Murdochf87a2032010-10-22 12:50:53 +01001051 intptr_t CommittedMemory() { return Capacity(); }
Steve Block3ce2e202009-11-05 08:53:23 +00001052
Steve Blocka7e24c12009-10-30 11:49:00 +00001053 // Available bytes without growing.
Ben Murdochf87a2032010-10-22 12:50:53 +01001054 intptr_t Available() { return accounting_stats_.Available(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001055
1056 // Allocated bytes in this space.
Ben Murdochf87a2032010-10-22 12:50:53 +01001057 virtual intptr_t Size() { return accounting_stats_.Size(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001058
1059 // Wasted bytes due to fragmentation and not recoverable until the
1060 // next GC of this space.
Ben Murdochf87a2032010-10-22 12:50:53 +01001061 intptr_t Waste() { return accounting_stats_.Waste(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001062
1063 // Returns the address of the first object in this space.
1064 Address bottom() { return first_page_->ObjectAreaStart(); }
1065
1066 // Returns the allocation pointer in this space.
1067 Address top() { return allocation_info_.top; }
1068
1069 // Allocate the requested number of bytes in the space if possible, return a
1070 // failure object if not.
John Reck59135872010-11-02 12:39:01 -07001071 MUST_USE_RESULT inline MaybeObject* AllocateRaw(int size_in_bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001072
1073 // Allocate the requested number of bytes for relocation during mark-compact
1074 // collection.
John Reck59135872010-11-02 12:39:01 -07001075 MUST_USE_RESULT inline MaybeObject* MCAllocateRaw(int size_in_bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001076
Leon Clarkee46be812010-01-19 14:06:41 +00001077 virtual bool ReserveSpace(int bytes);
1078
1079 // Used by ReserveSpace.
1080 virtual void PutRestOfCurrentPageOnFreeList(Page* current_page) = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00001081
Steve Block6ded16b2010-05-10 14:33:55 +01001082 // Free all pages in range from prev (exclusive) to last (inclusive).
1083 // Freed pages are moved to the end of page list.
1084 void FreePages(Page* prev, Page* last);
1085
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001086 // Deallocates a block.
1087 virtual void DeallocateBlock(Address start,
1088 int size_in_bytes,
1089 bool add_to_freelist) = 0;
1090
Steve Block6ded16b2010-05-10 14:33:55 +01001091 // Set space allocation info.
1092 void SetTop(Address top) {
1093 allocation_info_.top = top;
1094 allocation_info_.limit = PageAllocationLimit(Page::FromAllocationTop(top));
1095 }
1096
Steve Blocka7e24c12009-10-30 11:49:00 +00001097 // ---------------------------------------------------------------------------
1098 // Mark-compact collection support functions
1099
1100 // Set the relocation point to the beginning of the space.
1101 void MCResetRelocationInfo();
1102
1103 // Writes relocation info to the top page.
1104 void MCWriteRelocationInfoToPage() {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001105 TopPageOf(mc_forwarding_info_)->
1106 SetAllocationWatermark(mc_forwarding_info_.top);
Steve Blocka7e24c12009-10-30 11:49:00 +00001107 }
1108
1109 // Computes the offset of a given address in this space to the beginning
1110 // of the space.
1111 int MCSpaceOffsetForAddress(Address addr);
1112
1113 // Updates the allocation pointer to the relocation top after a mark-compact
1114 // collection.
1115 virtual void MCCommitRelocationInfo() = 0;
1116
1117 // Releases half of unused pages.
1118 void Shrink();
1119
1120 // Ensures that the capacity is at least 'capacity'. Returns false on failure.
1121 bool EnsureCapacity(int capacity);
1122
1123#ifdef ENABLE_HEAP_PROTECTION
1124 // Protect/unprotect the space by marking it read-only/writable.
1125 void Protect();
1126 void Unprotect();
1127#endif
1128
1129#ifdef DEBUG
1130 // Print meta info and objects in this space.
1131 virtual void Print();
1132
1133 // Verify integrity of this space.
1134 virtual void Verify(ObjectVisitor* visitor);
1135
1136 // Overridden by subclasses to verify space-specific object
1137 // properties (e.g., only maps or free-list nodes are in map space).
1138 virtual void VerifyObject(HeapObject* obj) {}
1139
1140 // Report code object related statistics
1141 void CollectCodeStatistics();
1142 static void ReportCodeStatistics();
1143 static void ResetCodeStatistics();
1144#endif
1145
Steve Block6ded16b2010-05-10 14:33:55 +01001146 // Returns the page of the allocation pointer.
1147 Page* AllocationTopPage() { return TopPageOf(allocation_info_); }
1148
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001149 void RelinkPageListInChunkOrder(bool deallocate_blocks);
1150
Steve Blocka7e24c12009-10-30 11:49:00 +00001151 protected:
1152 // Maximum capacity of this space.
Ben Murdochf87a2032010-10-22 12:50:53 +01001153 intptr_t max_capacity_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001154
1155 // Accounting information for this space.
1156 AllocationStats accounting_stats_;
1157
1158 // The first page in this space.
1159 Page* first_page_;
1160
1161 // The last page in this space. Initially set in Setup, updated in
1162 // Expand and Shrink.
1163 Page* last_page_;
1164
Steve Block6ded16b2010-05-10 14:33:55 +01001165 // True if pages owned by this space are linked in chunk-order.
1166 // See comment for class MemoryAllocator for definition of chunk-order.
1167 bool page_list_is_chunk_ordered_;
1168
Steve Blocka7e24c12009-10-30 11:49:00 +00001169 // Normal allocation information.
1170 AllocationInfo allocation_info_;
1171
1172 // Relocation information during mark-compact collections.
1173 AllocationInfo mc_forwarding_info_;
1174
1175 // Bytes of each page that cannot be allocated. Possibly non-zero
1176 // for pages in spaces with only fixed-size objects. Always zero
1177 // for pages in spaces with variable sized objects (those pages are
1178 // padded with free-list nodes).
1179 int page_extra_;
1180
1181 // Sets allocation pointer to a page bottom.
1182 static void SetAllocationInfo(AllocationInfo* alloc_info, Page* p);
1183
1184 // Returns the top page specified by an allocation info structure.
1185 static Page* TopPageOf(AllocationInfo alloc_info) {
1186 return Page::FromAllocationTop(alloc_info.limit);
1187 }
1188
Leon Clarked91b9f72010-01-27 17:25:45 +00001189 int CountPagesToTop() {
1190 Page* p = Page::FromAllocationTop(allocation_info_.top);
1191 PageIterator it(this, PageIterator::ALL_PAGES);
1192 int counter = 1;
1193 while (it.has_next()) {
1194 if (it.next() == p) return counter;
1195 counter++;
1196 }
1197 UNREACHABLE();
1198 return -1;
1199 }
1200
Steve Blocka7e24c12009-10-30 11:49:00 +00001201 // Expands the space by allocating a fixed number of pages. Returns false if
1202 // it cannot allocate requested number of pages from OS. Newly allocated
1203 // pages are append to the last_page;
1204 bool Expand(Page* last_page);
1205
1206 // Generic fast case allocation function that tries linear allocation in
1207 // the top page of 'alloc_info'. Returns NULL on failure.
1208 inline HeapObject* AllocateLinearly(AllocationInfo* alloc_info,
1209 int size_in_bytes);
1210
1211 // During normal allocation or deserialization, roll to the next page in
1212 // the space (there is assumed to be one) and allocate there. This
1213 // function is space-dependent.
1214 virtual HeapObject* AllocateInNextPage(Page* current_page,
1215 int size_in_bytes) = 0;
1216
1217 // Slow path of AllocateRaw. This function is space-dependent.
John Reck59135872010-11-02 12:39:01 -07001218 MUST_USE_RESULT virtual HeapObject* SlowAllocateRaw(int size_in_bytes) = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00001219
1220 // Slow path of MCAllocateRaw.
John Reck59135872010-11-02 12:39:01 -07001221 MUST_USE_RESULT HeapObject* SlowMCAllocateRaw(int size_in_bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001222
1223#ifdef DEBUG
Leon Clarkee46be812010-01-19 14:06:41 +00001224 // Returns the number of total pages in this space.
1225 int CountTotalPages();
Steve Blocka7e24c12009-10-30 11:49:00 +00001226#endif
1227 private:
Steve Blocka7e24c12009-10-30 11:49:00 +00001228
1229 // Returns a pointer to the page of the relocation pointer.
1230 Page* MCRelocationTopPage() { return TopPageOf(mc_forwarding_info_); }
1231
Steve Blocka7e24c12009-10-30 11:49:00 +00001232 friend class PageIterator;
1233};
1234
1235
1236#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1237class NumberAndSizeInfo BASE_EMBEDDED {
1238 public:
1239 NumberAndSizeInfo() : number_(0), bytes_(0) {}
1240
1241 int number() const { return number_; }
1242 void increment_number(int num) { number_ += num; }
1243
1244 int bytes() const { return bytes_; }
1245 void increment_bytes(int size) { bytes_ += size; }
1246
1247 void clear() {
1248 number_ = 0;
1249 bytes_ = 0;
1250 }
1251
1252 private:
1253 int number_;
1254 int bytes_;
1255};
1256
1257
1258// HistogramInfo class for recording a single "bar" of a histogram. This
1259// class is used for collecting statistics to print to stdout (when compiled
1260// with DEBUG) or to the log file (when compiled with
1261// ENABLE_LOGGING_AND_PROFILING).
1262class HistogramInfo: public NumberAndSizeInfo {
1263 public:
1264 HistogramInfo() : NumberAndSizeInfo() {}
1265
1266 const char* name() { return name_; }
1267 void set_name(const char* name) { name_ = name; }
1268
1269 private:
1270 const char* name_;
1271};
1272#endif
1273
1274
1275// -----------------------------------------------------------------------------
1276// SemiSpace in young generation
1277//
1278// A semispace is a contiguous chunk of memory. The mark-compact collector
1279// uses the memory in the from space as a marking stack when tracing live
1280// objects.
1281
1282class SemiSpace : public Space {
1283 public:
1284 // Constructor.
1285 SemiSpace() :Space(NEW_SPACE, NOT_EXECUTABLE) {
1286 start_ = NULL;
1287 age_mark_ = NULL;
1288 }
1289
1290 // Sets up the semispace using the given chunk.
1291 bool Setup(Address start, int initial_capacity, int maximum_capacity);
1292
1293 // Tear down the space. Heap memory was not allocated by the space, so it
1294 // is not deallocated here.
1295 void TearDown();
1296
1297 // True if the space has been set up but not torn down.
1298 bool HasBeenSetup() { return start_ != NULL; }
1299
1300 // Grow the size of the semispace by committing extra virtual memory.
1301 // Assumes that the caller has checked that the semispace has not reached
1302 // its maximum capacity (and thus there is space available in the reserved
1303 // address range to grow).
1304 bool Grow();
1305
1306 // Grow the semispace to the new capacity. The new capacity
1307 // requested must be larger than the current capacity.
1308 bool GrowTo(int new_capacity);
1309
1310 // Shrinks the semispace to the new capacity. The new capacity
1311 // requested must be more than the amount of used memory in the
1312 // semispace and less than the current capacity.
1313 bool ShrinkTo(int new_capacity);
1314
1315 // Returns the start address of the space.
1316 Address low() { return start_; }
1317 // Returns one past the end address of the space.
1318 Address high() { return low() + capacity_; }
1319
1320 // Age mark accessors.
1321 Address age_mark() { return age_mark_; }
1322 void set_age_mark(Address mark) { age_mark_ = mark; }
1323
1324 // True if the address is in the address range of this semispace (not
1325 // necessarily below the allocation pointer).
1326 bool Contains(Address a) {
1327 return (reinterpret_cast<uintptr_t>(a) & address_mask_)
1328 == reinterpret_cast<uintptr_t>(start_);
1329 }
1330
1331 // True if the object is a heap object in the address range of this
1332 // semispace (not necessarily below the allocation pointer).
1333 bool Contains(Object* o) {
1334 return (reinterpret_cast<uintptr_t>(o) & object_mask_) == object_expected_;
1335 }
1336
1337 // The offset of an address from the beginning of the space.
Steve Blockd0582a62009-12-15 09:54:21 +00001338 int SpaceOffsetForAddress(Address addr) {
1339 return static_cast<int>(addr - low());
1340 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001341
Leon Clarkee46be812010-01-19 14:06:41 +00001342 // If we don't have these here then SemiSpace will be abstract. However
1343 // they should never be called.
Ben Murdochf87a2032010-10-22 12:50:53 +01001344 virtual intptr_t Size() {
Steve Blocka7e24c12009-10-30 11:49:00 +00001345 UNREACHABLE();
1346 return 0;
1347 }
1348
Leon Clarkee46be812010-01-19 14:06:41 +00001349 virtual bool ReserveSpace(int bytes) {
1350 UNREACHABLE();
1351 return false;
1352 }
1353
Steve Blocka7e24c12009-10-30 11:49:00 +00001354 bool is_committed() { return committed_; }
1355 bool Commit();
1356 bool Uncommit();
1357
Steve Block6ded16b2010-05-10 14:33:55 +01001358#ifdef ENABLE_HEAP_PROTECTION
1359 // Protect/unprotect the space by marking it read-only/writable.
1360 virtual void Protect() {}
1361 virtual void Unprotect() {}
1362#endif
1363
Steve Blocka7e24c12009-10-30 11:49:00 +00001364#ifdef DEBUG
1365 virtual void Print();
1366 virtual void Verify();
1367#endif
1368
1369 // Returns the current capacity of the semi space.
1370 int Capacity() { return capacity_; }
1371
1372 // Returns the maximum capacity of the semi space.
1373 int MaximumCapacity() { return maximum_capacity_; }
1374
1375 // Returns the initial capacity of the semi space.
1376 int InitialCapacity() { return initial_capacity_; }
1377
1378 private:
1379 // The current and maximum capacity of the space.
1380 int capacity_;
1381 int maximum_capacity_;
1382 int initial_capacity_;
1383
1384 // The start address of the space.
1385 Address start_;
1386 // Used to govern object promotion during mark-compact collection.
1387 Address age_mark_;
1388
1389 // Masks and comparison values to test for containment in this semispace.
1390 uintptr_t address_mask_;
1391 uintptr_t object_mask_;
1392 uintptr_t object_expected_;
1393
1394 bool committed_;
1395
1396 public:
1397 TRACK_MEMORY("SemiSpace")
1398};
1399
1400
1401// A SemiSpaceIterator is an ObjectIterator that iterates over the active
1402// semispace of the heap's new space. It iterates over the objects in the
1403// semispace from a given start address (defaulting to the bottom of the
1404// semispace) to the top of the semispace. New objects allocated after the
1405// iterator is created are not iterated.
1406class SemiSpaceIterator : public ObjectIterator {
1407 public:
1408 // Create an iterator over the objects in the given space. If no start
1409 // address is given, the iterator starts from the bottom of the space. If
1410 // no size function is given, the iterator calls Object::Size().
1411 explicit SemiSpaceIterator(NewSpace* space);
1412 SemiSpaceIterator(NewSpace* space, HeapObjectCallback size_func);
1413 SemiSpaceIterator(NewSpace* space, Address start);
1414
Steve Blocka7e24c12009-10-30 11:49:00 +00001415 HeapObject* next() {
Leon Clarked91b9f72010-01-27 17:25:45 +00001416 if (current_ == limit_) return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00001417
1418 HeapObject* object = HeapObject::FromAddress(current_);
1419 int size = (size_func_ == NULL) ? object->Size() : size_func_(object);
1420
1421 current_ += size;
1422 return object;
1423 }
1424
1425 // Implementation of the ObjectIterator functions.
Steve Blocka7e24c12009-10-30 11:49:00 +00001426 virtual HeapObject* next_object() { return next(); }
1427
1428 private:
1429 void Initialize(NewSpace* space, Address start, Address end,
1430 HeapObjectCallback size_func);
1431
1432 // The semispace.
1433 SemiSpace* space_;
1434 // The current iteration point.
1435 Address current_;
1436 // The end of iteration.
1437 Address limit_;
1438 // The callback function.
1439 HeapObjectCallback size_func_;
1440};
1441
1442
1443// -----------------------------------------------------------------------------
1444// The young generation space.
1445//
1446// The new space consists of a contiguous pair of semispaces. It simply
1447// forwards most functions to the appropriate semispace.
1448
1449class NewSpace : public Space {
1450 public:
1451 // Constructor.
1452 NewSpace() : Space(NEW_SPACE, NOT_EXECUTABLE) {}
1453
1454 // Sets up the new space using the given chunk.
1455 bool Setup(Address start, int size);
1456
1457 // Tears down the space. Heap memory was not allocated by the space, so it
1458 // is not deallocated here.
1459 void TearDown();
1460
1461 // True if the space has been set up but not torn down.
1462 bool HasBeenSetup() {
1463 return to_space_.HasBeenSetup() && from_space_.HasBeenSetup();
1464 }
1465
1466 // Flip the pair of spaces.
1467 void Flip();
1468
1469 // Grow the capacity of the semispaces. Assumes that they are not at
1470 // their maximum capacity.
1471 void Grow();
1472
1473 // Shrink the capacity of the semispaces.
1474 void Shrink();
1475
1476 // True if the address or object lies in the address range of either
1477 // semispace (not necessarily below the allocation pointer).
1478 bool Contains(Address a) {
1479 return (reinterpret_cast<uintptr_t>(a) & address_mask_)
1480 == reinterpret_cast<uintptr_t>(start_);
1481 }
1482 bool Contains(Object* o) {
1483 return (reinterpret_cast<uintptr_t>(o) & object_mask_) == object_expected_;
1484 }
1485
1486 // Return the allocated bytes in the active semispace.
Ben Murdochf87a2032010-10-22 12:50:53 +01001487 virtual intptr_t Size() { return static_cast<int>(top() - bottom()); }
1488 // The same, but returning an int. We have to have the one that returns
1489 // intptr_t because it is inherited, but if we know we are dealing with the
1490 // new space, which can't get as big as the other spaces then this is useful:
1491 int SizeAsInt() { return static_cast<int>(Size()); }
Steve Block3ce2e202009-11-05 08:53:23 +00001492
Steve Blocka7e24c12009-10-30 11:49:00 +00001493 // Return the current capacity of a semispace.
Ben Murdochf87a2032010-10-22 12:50:53 +01001494 intptr_t Capacity() {
Steve Blocka7e24c12009-10-30 11:49:00 +00001495 ASSERT(to_space_.Capacity() == from_space_.Capacity());
1496 return to_space_.Capacity();
1497 }
Steve Block3ce2e202009-11-05 08:53:23 +00001498
1499 // Return the total amount of memory committed for new space.
Ben Murdochf87a2032010-10-22 12:50:53 +01001500 intptr_t CommittedMemory() {
Steve Block3ce2e202009-11-05 08:53:23 +00001501 if (from_space_.is_committed()) return 2 * Capacity();
1502 return Capacity();
1503 }
1504
Steve Blocka7e24c12009-10-30 11:49:00 +00001505 // Return the available bytes without growing in the active semispace.
Ben Murdochf87a2032010-10-22 12:50:53 +01001506 intptr_t Available() { return Capacity() - Size(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001507
1508 // Return the maximum capacity of a semispace.
1509 int MaximumCapacity() {
1510 ASSERT(to_space_.MaximumCapacity() == from_space_.MaximumCapacity());
1511 return to_space_.MaximumCapacity();
1512 }
1513
1514 // Returns the initial capacity of a semispace.
1515 int InitialCapacity() {
1516 ASSERT(to_space_.InitialCapacity() == from_space_.InitialCapacity());
1517 return to_space_.InitialCapacity();
1518 }
1519
1520 // Return the address of the allocation pointer in the active semispace.
1521 Address top() { return allocation_info_.top; }
1522 // Return the address of the first object in the active semispace.
1523 Address bottom() { return to_space_.low(); }
1524
1525 // Get the age mark of the inactive semispace.
1526 Address age_mark() { return from_space_.age_mark(); }
1527 // Set the age mark in the active semispace.
1528 void set_age_mark(Address mark) { to_space_.set_age_mark(mark); }
1529
1530 // The start address of the space and a bit mask. Anding an address in the
1531 // new space with the mask will result in the start address.
1532 Address start() { return start_; }
1533 uintptr_t mask() { return address_mask_; }
1534
1535 // The allocation top and limit addresses.
1536 Address* allocation_top_address() { return &allocation_info_.top; }
1537 Address* allocation_limit_address() { return &allocation_info_.limit; }
1538
John Reck59135872010-11-02 12:39:01 -07001539 MUST_USE_RESULT MaybeObject* AllocateRaw(int size_in_bytes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001540 return AllocateRawInternal(size_in_bytes, &allocation_info_);
1541 }
1542
1543 // Allocate the requested number of bytes for relocation during mark-compact
1544 // collection.
John Reck59135872010-11-02 12:39:01 -07001545 MUST_USE_RESULT MaybeObject* MCAllocateRaw(int size_in_bytes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001546 return AllocateRawInternal(size_in_bytes, &mc_forwarding_info_);
1547 }
1548
1549 // Reset the allocation pointer to the beginning of the active semispace.
1550 void ResetAllocationInfo();
1551 // Reset the reloction pointer to the bottom of the inactive semispace in
1552 // preparation for mark-compact collection.
1553 void MCResetRelocationInfo();
1554 // Update the allocation pointer in the active semispace after a
1555 // mark-compact collection.
1556 void MCCommitRelocationInfo();
1557
1558 // Get the extent of the inactive semispace (for use as a marking stack).
1559 Address FromSpaceLow() { return from_space_.low(); }
1560 Address FromSpaceHigh() { return from_space_.high(); }
1561
1562 // Get the extent of the active semispace (to sweep newly copied objects
1563 // during a scavenge collection).
1564 Address ToSpaceLow() { return to_space_.low(); }
1565 Address ToSpaceHigh() { return to_space_.high(); }
1566
1567 // Offsets from the beginning of the semispaces.
1568 int ToSpaceOffsetForAddress(Address a) {
1569 return to_space_.SpaceOffsetForAddress(a);
1570 }
1571 int FromSpaceOffsetForAddress(Address a) {
1572 return from_space_.SpaceOffsetForAddress(a);
1573 }
1574
1575 // True if the object is a heap object in the address range of the
1576 // respective semispace (not necessarily below the allocation pointer of the
1577 // semispace).
1578 bool ToSpaceContains(Object* o) { return to_space_.Contains(o); }
1579 bool FromSpaceContains(Object* o) { return from_space_.Contains(o); }
1580
1581 bool ToSpaceContains(Address a) { return to_space_.Contains(a); }
1582 bool FromSpaceContains(Address a) { return from_space_.Contains(a); }
1583
Leon Clarkee46be812010-01-19 14:06:41 +00001584 virtual bool ReserveSpace(int bytes);
1585
Steve Blocka7e24c12009-10-30 11:49:00 +00001586#ifdef ENABLE_HEAP_PROTECTION
1587 // Protect/unprotect the space by marking it read-only/writable.
1588 virtual void Protect();
1589 virtual void Unprotect();
1590#endif
1591
1592#ifdef DEBUG
1593 // Verify the active semispace.
1594 virtual void Verify();
1595 // Print the active semispace.
1596 virtual void Print() { to_space_.Print(); }
1597#endif
1598
1599#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1600 // Iterates the active semispace to collect statistics.
1601 void CollectStatistics();
1602 // Reports previously collected statistics of the active semispace.
1603 void ReportStatistics();
1604 // Clears previously collected statistics.
1605 void ClearHistograms();
1606
1607 // Record the allocation or promotion of a heap object. Note that we don't
1608 // record every single allocation, but only those that happen in the
1609 // to space during a scavenge GC.
1610 void RecordAllocation(HeapObject* obj);
1611 void RecordPromotion(HeapObject* obj);
1612#endif
1613
1614 // Return whether the operation succeded.
1615 bool CommitFromSpaceIfNeeded() {
1616 if (from_space_.is_committed()) return true;
1617 return from_space_.Commit();
1618 }
1619
1620 bool UncommitFromSpace() {
1621 if (!from_space_.is_committed()) return true;
1622 return from_space_.Uncommit();
1623 }
1624
1625 private:
1626 // The semispaces.
1627 SemiSpace to_space_;
1628 SemiSpace from_space_;
1629
1630 // Start address and bit mask for containment testing.
1631 Address start_;
1632 uintptr_t address_mask_;
1633 uintptr_t object_mask_;
1634 uintptr_t object_expected_;
1635
1636 // Allocation pointer and limit for normal allocation and allocation during
1637 // mark-compact collection.
1638 AllocationInfo allocation_info_;
1639 AllocationInfo mc_forwarding_info_;
1640
1641#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1642 HistogramInfo* allocated_histogram_;
1643 HistogramInfo* promoted_histogram_;
1644#endif
1645
1646 // Implementation of AllocateRaw and MCAllocateRaw.
John Reck59135872010-11-02 12:39:01 -07001647 MUST_USE_RESULT inline MaybeObject* AllocateRawInternal(
1648 int size_in_bytes,
1649 AllocationInfo* alloc_info);
Steve Blocka7e24c12009-10-30 11:49:00 +00001650
1651 friend class SemiSpaceIterator;
1652
1653 public:
1654 TRACK_MEMORY("NewSpace")
1655};
1656
1657
1658// -----------------------------------------------------------------------------
1659// Free lists for old object spaces
1660//
1661// Free-list nodes are free blocks in the heap. They look like heap objects
1662// (free-list node pointers have the heap object tag, and they have a map like
1663// a heap object). They have a size and a next pointer. The next pointer is
1664// the raw address of the next free list node (or NULL).
1665class FreeListNode: public HeapObject {
1666 public:
1667 // Obtain a free-list node from a raw address. This is not a cast because
1668 // it does not check nor require that the first word at the address is a map
1669 // pointer.
1670 static FreeListNode* FromAddress(Address address) {
1671 return reinterpret_cast<FreeListNode*>(HeapObject::FromAddress(address));
1672 }
1673
Steve Block3ce2e202009-11-05 08:53:23 +00001674 static inline bool IsFreeListNode(HeapObject* object);
1675
Steve Blocka7e24c12009-10-30 11:49:00 +00001676 // Set the size in bytes, which can be read with HeapObject::Size(). This
1677 // function also writes a map to the first word of the block so that it
1678 // looks like a heap object to the garbage collector and heap iteration
1679 // functions.
1680 void set_size(int size_in_bytes);
1681
1682 // Accessors for the next field.
1683 inline Address next();
1684 inline void set_next(Address next);
1685
1686 private:
1687 static const int kNextOffset = POINTER_SIZE_ALIGN(ByteArray::kHeaderSize);
1688
1689 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeListNode);
1690};
1691
1692
1693// The free list for the old space.
1694class OldSpaceFreeList BASE_EMBEDDED {
1695 public:
1696 explicit OldSpaceFreeList(AllocationSpace owner);
1697
1698 // Clear the free list.
1699 void Reset();
1700
1701 // Return the number of bytes available on the free list.
Ben Murdochf87a2032010-10-22 12:50:53 +01001702 intptr_t available() { return available_; }
Steve Blocka7e24c12009-10-30 11:49:00 +00001703
1704 // Place a node on the free list. The block of size 'size_in_bytes'
1705 // starting at 'start' is placed on the free list. The return value is the
1706 // number of bytes that have been lost due to internal fragmentation by
1707 // freeing the block. Bookkeeping information will be written to the block,
1708 // ie, its contents will be destroyed. The start address should be word
1709 // aligned, and the size should be a non-zero multiple of the word size.
1710 int Free(Address start, int size_in_bytes);
1711
1712 // Allocate a block of size 'size_in_bytes' from the free list. The block
1713 // is unitialized. A failure is returned if no block is available. The
1714 // number of bytes lost to fragmentation is returned in the output parameter
1715 // 'wasted_bytes'. The size should be a non-zero multiple of the word size.
John Reck59135872010-11-02 12:39:01 -07001716 MUST_USE_RESULT MaybeObject* Allocate(int size_in_bytes, int* wasted_bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001717
1718 private:
1719 // The size range of blocks, in bytes. (Smaller allocations are allowed, but
1720 // will always result in waste.)
1721 static const int kMinBlockSize = 2 * kPointerSize;
1722 static const int kMaxBlockSize = Page::kMaxHeapObjectSize;
1723
1724 // The identity of the owning space, for building allocation Failure
1725 // objects.
1726 AllocationSpace owner_;
1727
1728 // Total available bytes in all blocks on this free list.
1729 int available_;
1730
1731 // Blocks are put on exact free lists in an array, indexed by size in words.
1732 // The available sizes are kept in an increasingly ordered list. Entries
1733 // corresponding to sizes < kMinBlockSize always have an empty free list
1734 // (but index kHead is used for the head of the size list).
1735 struct SizeNode {
1736 // Address of the head FreeListNode of the implied block size or NULL.
1737 Address head_node_;
1738 // Size (words) of the next larger available size if head_node_ != NULL.
1739 int next_size_;
1740 };
1741 static const int kFreeListsLength = kMaxBlockSize / kPointerSize + 1;
1742 SizeNode free_[kFreeListsLength];
1743
1744 // Sentinel elements for the size list. Real elements are in ]kHead..kEnd[.
1745 static const int kHead = kMinBlockSize / kPointerSize - 1;
1746 static const int kEnd = kMaxInt;
1747
1748 // We keep a "finger" in the size list to speed up a common pattern:
1749 // repeated requests for the same or increasing sizes.
1750 int finger_;
1751
1752 // Starting from *prev, find and return the smallest size >= index (words),
1753 // or kEnd. Update *prev to be the largest size < index, or kHead.
1754 int FindSize(int index, int* prev) {
1755 int cur = free_[*prev].next_size_;
1756 while (cur < index) {
1757 *prev = cur;
1758 cur = free_[cur].next_size_;
1759 }
1760 return cur;
1761 }
1762
1763 // Remove an existing element from the size list.
1764 void RemoveSize(int index) {
1765 int prev = kHead;
1766 int cur = FindSize(index, &prev);
1767 ASSERT(cur == index);
1768 free_[prev].next_size_ = free_[cur].next_size_;
1769 finger_ = prev;
1770 }
1771
1772 // Insert a new element into the size list.
1773 void InsertSize(int index) {
1774 int prev = kHead;
1775 int cur = FindSize(index, &prev);
1776 ASSERT(cur != index);
1777 free_[prev].next_size_ = index;
1778 free_[index].next_size_ = cur;
1779 }
1780
1781 // The size list is not updated during a sequence of calls to Free, but is
1782 // rebuilt before the next allocation.
1783 void RebuildSizeList();
1784 bool needs_rebuild_;
1785
1786#ifdef DEBUG
1787 // Does this free list contain a free block located at the address of 'node'?
1788 bool Contains(FreeListNode* node);
1789#endif
1790
1791 DISALLOW_COPY_AND_ASSIGN(OldSpaceFreeList);
1792};
1793
1794
1795// The free list for the map space.
1796class FixedSizeFreeList BASE_EMBEDDED {
1797 public:
1798 FixedSizeFreeList(AllocationSpace owner, int object_size);
1799
1800 // Clear the free list.
1801 void Reset();
1802
1803 // Return the number of bytes available on the free list.
Ben Murdochf87a2032010-10-22 12:50:53 +01001804 intptr_t available() { return available_; }
Steve Blocka7e24c12009-10-30 11:49:00 +00001805
1806 // Place a node on the free list. The block starting at 'start' (assumed to
1807 // have size object_size_) is placed on the free list. Bookkeeping
1808 // information will be written to the block, ie, its contents will be
1809 // destroyed. The start address should be word aligned.
1810 void Free(Address start);
1811
1812 // Allocate a fixed sized block from the free list. The block is unitialized.
1813 // A failure is returned if no block is available.
John Reck59135872010-11-02 12:39:01 -07001814 MUST_USE_RESULT MaybeObject* Allocate();
Steve Blocka7e24c12009-10-30 11:49:00 +00001815
1816 private:
1817 // Available bytes on the free list.
Ben Murdochf87a2032010-10-22 12:50:53 +01001818 intptr_t available_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001819
1820 // The head of the free list.
1821 Address head_;
1822
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001823 // The tail of the free list.
1824 Address tail_;
1825
Steve Blocka7e24c12009-10-30 11:49:00 +00001826 // The identity of the owning space, for building allocation Failure
1827 // objects.
1828 AllocationSpace owner_;
1829
1830 // The size of the objects in this space.
1831 int object_size_;
1832
1833 DISALLOW_COPY_AND_ASSIGN(FixedSizeFreeList);
1834};
1835
1836
1837// -----------------------------------------------------------------------------
1838// Old object space (excluding map objects)
1839
1840class OldSpace : public PagedSpace {
1841 public:
1842 // Creates an old space object with a given maximum capacity.
1843 // The constructor does not allocate pages from OS.
Ben Murdochf87a2032010-10-22 12:50:53 +01001844 explicit OldSpace(intptr_t max_capacity,
Steve Blocka7e24c12009-10-30 11:49:00 +00001845 AllocationSpace id,
1846 Executability executable)
1847 : PagedSpace(max_capacity, id, executable), free_list_(id) {
1848 page_extra_ = 0;
1849 }
1850
1851 // The bytes available on the free list (ie, not above the linear allocation
1852 // pointer).
Ben Murdochf87a2032010-10-22 12:50:53 +01001853 intptr_t AvailableFree() { return free_list_.available(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001854
Steve Block6ded16b2010-05-10 14:33:55 +01001855 // The limit of allocation for a page in this space.
1856 virtual Address PageAllocationLimit(Page* page) {
1857 return page->ObjectAreaEnd();
Steve Blocka7e24c12009-10-30 11:49:00 +00001858 }
1859
1860 // Give a block of memory to the space's free list. It might be added to
1861 // the free list or accounted as waste.
Steve Block6ded16b2010-05-10 14:33:55 +01001862 // If add_to_freelist is false then just accounting stats are updated and
1863 // no attempt to add area to free list is made.
1864 void Free(Address start, int size_in_bytes, bool add_to_freelist) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001865 accounting_stats_.DeallocateBytes(size_in_bytes);
Steve Block6ded16b2010-05-10 14:33:55 +01001866
1867 if (add_to_freelist) {
1868 int wasted_bytes = free_list_.Free(start, size_in_bytes);
1869 accounting_stats_.WasteBytes(wasted_bytes);
1870 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001871 }
1872
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001873 virtual void DeallocateBlock(Address start,
1874 int size_in_bytes,
1875 bool add_to_freelist);
1876
Steve Blocka7e24c12009-10-30 11:49:00 +00001877 // Prepare for full garbage collection. Resets the relocation pointer and
1878 // clears the free list.
1879 virtual void PrepareForMarkCompact(bool will_compact);
1880
1881 // Updates the allocation pointer to the relocation top after a mark-compact
1882 // collection.
1883 virtual void MCCommitRelocationInfo();
1884
Leon Clarkee46be812010-01-19 14:06:41 +00001885 virtual void PutRestOfCurrentPageOnFreeList(Page* current_page);
1886
Steve Blocka7e24c12009-10-30 11:49:00 +00001887#ifdef DEBUG
1888 // Reports statistics for the space
1889 void ReportStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00001890#endif
1891
1892 protected:
1893 // Virtual function in the superclass. Slow path of AllocateRaw.
John Reck59135872010-11-02 12:39:01 -07001894 MUST_USE_RESULT HeapObject* SlowAllocateRaw(int size_in_bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001895
1896 // Virtual function in the superclass. Allocate linearly at the start of
1897 // the page after current_page (there is assumed to be one).
1898 HeapObject* AllocateInNextPage(Page* current_page, int size_in_bytes);
1899
1900 private:
1901 // The space's free list.
1902 OldSpaceFreeList free_list_;
1903
1904 public:
1905 TRACK_MEMORY("OldSpace")
1906};
1907
1908
1909// -----------------------------------------------------------------------------
1910// Old space for objects of a fixed size
1911
1912class FixedSpace : public PagedSpace {
1913 public:
Ben Murdochf87a2032010-10-22 12:50:53 +01001914 FixedSpace(intptr_t max_capacity,
Steve Blocka7e24c12009-10-30 11:49:00 +00001915 AllocationSpace id,
1916 int object_size_in_bytes,
1917 const char* name)
1918 : PagedSpace(max_capacity, id, NOT_EXECUTABLE),
1919 object_size_in_bytes_(object_size_in_bytes),
1920 name_(name),
1921 free_list_(id, object_size_in_bytes) {
1922 page_extra_ = Page::kObjectAreaSize % object_size_in_bytes;
1923 }
1924
Steve Block6ded16b2010-05-10 14:33:55 +01001925 // The limit of allocation for a page in this space.
1926 virtual Address PageAllocationLimit(Page* page) {
1927 return page->ObjectAreaEnd() - page_extra_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001928 }
1929
1930 int object_size_in_bytes() { return object_size_in_bytes_; }
1931
1932 // Give a fixed sized block of memory to the space's free list.
Steve Block6ded16b2010-05-10 14:33:55 +01001933 // If add_to_freelist is false then just accounting stats are updated and
1934 // no attempt to add area to free list is made.
1935 void Free(Address start, bool add_to_freelist) {
1936 if (add_to_freelist) {
1937 free_list_.Free(start);
1938 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001939 accounting_stats_.DeallocateBytes(object_size_in_bytes_);
1940 }
1941
1942 // Prepares for a mark-compact GC.
1943 virtual void PrepareForMarkCompact(bool will_compact);
1944
1945 // Updates the allocation pointer to the relocation top after a mark-compact
1946 // collection.
1947 virtual void MCCommitRelocationInfo();
1948
Leon Clarkee46be812010-01-19 14:06:41 +00001949 virtual void PutRestOfCurrentPageOnFreeList(Page* current_page);
1950
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001951 virtual void DeallocateBlock(Address start,
1952 int size_in_bytes,
1953 bool add_to_freelist);
Steve Blocka7e24c12009-10-30 11:49:00 +00001954#ifdef DEBUG
1955 // Reports statistic info of the space
1956 void ReportStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00001957#endif
1958
1959 protected:
1960 // Virtual function in the superclass. Slow path of AllocateRaw.
John Reck59135872010-11-02 12:39:01 -07001961 MUST_USE_RESULT HeapObject* SlowAllocateRaw(int size_in_bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001962
1963 // Virtual function in the superclass. Allocate linearly at the start of
1964 // the page after current_page (there is assumed to be one).
1965 HeapObject* AllocateInNextPage(Page* current_page, int size_in_bytes);
1966
Leon Clarkee46be812010-01-19 14:06:41 +00001967 void ResetFreeList() {
1968 free_list_.Reset();
1969 }
1970
Steve Blocka7e24c12009-10-30 11:49:00 +00001971 private:
1972 // The size of objects in this space.
1973 int object_size_in_bytes_;
1974
1975 // The name of this space.
1976 const char* name_;
1977
1978 // The space's free list.
1979 FixedSizeFreeList free_list_;
1980};
1981
1982
1983// -----------------------------------------------------------------------------
1984// Old space for all map objects
1985
1986class MapSpace : public FixedSpace {
1987 public:
1988 // Creates a map space object with a maximum capacity.
Ben Murdochf87a2032010-10-22 12:50:53 +01001989 MapSpace(intptr_t max_capacity, int max_map_space_pages, AllocationSpace id)
Leon Clarked91b9f72010-01-27 17:25:45 +00001990 : FixedSpace(max_capacity, id, Map::kSize, "map"),
1991 max_map_space_pages_(max_map_space_pages) {
1992 ASSERT(max_map_space_pages < kMaxMapPageIndex);
1993 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001994
1995 // Prepares for a mark-compact GC.
1996 virtual void PrepareForMarkCompact(bool will_compact);
1997
1998 // Given an index, returns the page address.
1999 Address PageAddress(int page_index) { return page_addresses_[page_index]; }
2000
Leon Clarked91b9f72010-01-27 17:25:45 +00002001 static const int kMaxMapPageIndex = 1 << MapWord::kMapPageIndexBits;
Steve Blocka7e24c12009-10-30 11:49:00 +00002002
Leon Clarkee46be812010-01-19 14:06:41 +00002003 // Are map pointers encodable into map word?
2004 bool MapPointersEncodable() {
2005 if (!FLAG_use_big_map_space) {
Leon Clarked91b9f72010-01-27 17:25:45 +00002006 ASSERT(CountPagesToTop() <= kMaxMapPageIndex);
Leon Clarkee46be812010-01-19 14:06:41 +00002007 return true;
2008 }
Leon Clarked91b9f72010-01-27 17:25:45 +00002009 return CountPagesToTop() <= max_map_space_pages_;
Leon Clarkee46be812010-01-19 14:06:41 +00002010 }
2011
2012 // Should be called after forced sweep to find out if map space needs
2013 // compaction.
2014 bool NeedsCompaction(int live_maps) {
Leon Clarked91b9f72010-01-27 17:25:45 +00002015 return !MapPointersEncodable() && live_maps <= CompactionThreshold();
Leon Clarkee46be812010-01-19 14:06:41 +00002016 }
2017
2018 Address TopAfterCompaction(int live_maps) {
2019 ASSERT(NeedsCompaction(live_maps));
2020
2021 int pages_left = live_maps / kMapsPerPage;
2022 PageIterator it(this, PageIterator::ALL_PAGES);
2023 while (pages_left-- > 0) {
2024 ASSERT(it.has_next());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002025 it.next()->SetRegionMarks(Page::kAllRegionsCleanMarks);
Leon Clarkee46be812010-01-19 14:06:41 +00002026 }
2027 ASSERT(it.has_next());
2028 Page* top_page = it.next();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002029 top_page->SetRegionMarks(Page::kAllRegionsCleanMarks);
Leon Clarkee46be812010-01-19 14:06:41 +00002030 ASSERT(top_page->is_valid());
2031
2032 int offset = live_maps % kMapsPerPage * Map::kSize;
2033 Address top = top_page->ObjectAreaStart() + offset;
2034 ASSERT(top < top_page->ObjectAreaEnd());
2035 ASSERT(Contains(top));
2036
2037 return top;
2038 }
2039
2040 void FinishCompaction(Address new_top, int live_maps) {
2041 Page* top_page = Page::FromAddress(new_top);
2042 ASSERT(top_page->is_valid());
2043
2044 SetAllocationInfo(&allocation_info_, top_page);
2045 allocation_info_.top = new_top;
2046
2047 int new_size = live_maps * Map::kSize;
2048 accounting_stats_.DeallocateBytes(accounting_stats_.Size());
2049 accounting_stats_.AllocateBytes(new_size);
2050
2051#ifdef DEBUG
2052 if (FLAG_enable_slow_asserts) {
Leon Clarked91b9f72010-01-27 17:25:45 +00002053 intptr_t actual_size = 0;
Leon Clarkee46be812010-01-19 14:06:41 +00002054 for (Page* p = first_page_; p != top_page; p = p->next_page())
2055 actual_size += kMapsPerPage * Map::kSize;
2056 actual_size += (new_top - top_page->ObjectAreaStart());
2057 ASSERT(accounting_stats_.Size() == actual_size);
2058 }
2059#endif
2060
2061 Shrink();
2062 ResetFreeList();
2063 }
2064
Steve Blocka7e24c12009-10-30 11:49:00 +00002065 protected:
2066#ifdef DEBUG
2067 virtual void VerifyObject(HeapObject* obj);
2068#endif
2069
2070 private:
Leon Clarkee46be812010-01-19 14:06:41 +00002071 static const int kMapsPerPage = Page::kObjectAreaSize / Map::kSize;
2072
2073 // Do map space compaction if there is a page gap.
Leon Clarked91b9f72010-01-27 17:25:45 +00002074 int CompactionThreshold() {
2075 return kMapsPerPage * (max_map_space_pages_ - 1);
2076 }
2077
2078 const int max_map_space_pages_;
Leon Clarkee46be812010-01-19 14:06:41 +00002079
Steve Blocka7e24c12009-10-30 11:49:00 +00002080 // An array of page start address in a map space.
Leon Clarked91b9f72010-01-27 17:25:45 +00002081 Address page_addresses_[kMaxMapPageIndex];
Steve Blocka7e24c12009-10-30 11:49:00 +00002082
2083 public:
2084 TRACK_MEMORY("MapSpace")
2085};
2086
2087
2088// -----------------------------------------------------------------------------
2089// Old space for all global object property cell objects
2090
2091class CellSpace : public FixedSpace {
2092 public:
2093 // Creates a property cell space object with a maximum capacity.
Ben Murdochf87a2032010-10-22 12:50:53 +01002094 CellSpace(intptr_t max_capacity, AllocationSpace id)
Steve Blocka7e24c12009-10-30 11:49:00 +00002095 : FixedSpace(max_capacity, id, JSGlobalPropertyCell::kSize, "cell") {}
2096
2097 protected:
2098#ifdef DEBUG
2099 virtual void VerifyObject(HeapObject* obj);
2100#endif
2101
2102 public:
2103 TRACK_MEMORY("CellSpace")
2104};
2105
2106
2107// -----------------------------------------------------------------------------
2108// Large objects ( > Page::kMaxHeapObjectSize ) are allocated and managed by
2109// the large object space. A large object is allocated from OS heap with
2110// extra padding bytes (Page::kPageSize + Page::kObjectStartOffset).
2111// A large object always starts at Page::kObjectStartOffset to a page.
2112// Large objects do not move during garbage collections.
2113
2114// A LargeObjectChunk holds exactly one large object page with exactly one
2115// large object.
2116class LargeObjectChunk {
2117 public:
2118 // Allocates a new LargeObjectChunk that contains a large object page
2119 // (Page::kPageSize aligned) that has at least size_in_bytes (for a large
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002120 // object) bytes after the object area start of that page.
2121 // The allocated chunk size is set in the output parameter chunk_size.
Steve Blocka7e24c12009-10-30 11:49:00 +00002122 static LargeObjectChunk* New(int size_in_bytes,
2123 size_t* chunk_size,
2124 Executability executable);
2125
2126 // Interpret a raw address as a large object chunk.
2127 static LargeObjectChunk* FromAddress(Address address) {
2128 return reinterpret_cast<LargeObjectChunk*>(address);
2129 }
2130
2131 // Returns the address of this chunk.
2132 Address address() { return reinterpret_cast<Address>(this); }
2133
2134 // Accessors for the fields of the chunk.
2135 LargeObjectChunk* next() { return next_; }
2136 void set_next(LargeObjectChunk* chunk) { next_ = chunk; }
2137
Steve Block791712a2010-08-27 10:21:07 +01002138 size_t size() { return size_ & ~Page::kPageFlagMask; }
Steve Blocka7e24c12009-10-30 11:49:00 +00002139 void set_size(size_t size_in_bytes) { size_ = size_in_bytes; }
2140
2141 // Returns the object in this chunk.
2142 inline HeapObject* GetObject();
2143
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002144 // Given a requested size returns the physical size of a chunk to be
2145 // allocated.
Steve Blocka7e24c12009-10-30 11:49:00 +00002146 static int ChunkSizeFor(int size_in_bytes);
2147
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002148 // Given a chunk size, returns the object size it can accommodate. Used by
2149 // LargeObjectSpace::Available.
Ben Murdochf87a2032010-10-22 12:50:53 +01002150 static intptr_t ObjectSizeFor(intptr_t chunk_size) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002151 if (chunk_size <= (Page::kPageSize + Page::kObjectStartOffset)) return 0;
2152 return chunk_size - Page::kPageSize - Page::kObjectStartOffset;
2153 }
2154
2155 private:
2156 // A pointer to the next large object chunk in the space or NULL.
2157 LargeObjectChunk* next_;
2158
2159 // The size of this chunk.
2160 size_t size_;
2161
2162 public:
2163 TRACK_MEMORY("LargeObjectChunk")
2164};
2165
2166
2167class LargeObjectSpace : public Space {
2168 public:
2169 explicit LargeObjectSpace(AllocationSpace id);
2170 virtual ~LargeObjectSpace() {}
2171
2172 // Initializes internal data structures.
2173 bool Setup();
2174
2175 // Releases internal resources, frees objects in this space.
2176 void TearDown();
2177
2178 // Allocates a (non-FixedArray, non-Code) large object.
John Reck59135872010-11-02 12:39:01 -07002179 MUST_USE_RESULT MaybeObject* AllocateRaw(int size_in_bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00002180 // Allocates a large Code object.
John Reck59135872010-11-02 12:39:01 -07002181 MUST_USE_RESULT MaybeObject* AllocateRawCode(int size_in_bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00002182 // Allocates a large FixedArray.
John Reck59135872010-11-02 12:39:01 -07002183 MUST_USE_RESULT MaybeObject* AllocateRawFixedArray(int size_in_bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00002184
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002185 // Available bytes for objects in this space.
Ben Murdochf87a2032010-10-22 12:50:53 +01002186 intptr_t Available() {
Steve Blocka7e24c12009-10-30 11:49:00 +00002187 return LargeObjectChunk::ObjectSizeFor(MemoryAllocator::Available());
2188 }
2189
Ben Murdochf87a2032010-10-22 12:50:53 +01002190 virtual intptr_t Size() {
Steve Blocka7e24c12009-10-30 11:49:00 +00002191 return size_;
2192 }
2193
2194 int PageCount() {
2195 return page_count_;
2196 }
2197
2198 // Finds an object for a given address, returns Failure::Exception()
2199 // if it is not found. The function iterates through all objects in this
2200 // space, may be slow.
John Reck59135872010-11-02 12:39:01 -07002201 MaybeObject* FindObject(Address a);
Steve Blocka7e24c12009-10-30 11:49:00 +00002202
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002203 // Finds a large object page containing the given pc, returns NULL
2204 // if such a page doesn't exist.
2205 LargeObjectChunk* FindChunkContainingPc(Address pc);
2206
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002207 // Iterates objects covered by dirty regions.
2208 void IterateDirtyRegions(ObjectSlotCallback func);
Steve Blocka7e24c12009-10-30 11:49:00 +00002209
2210 // Frees unmarked objects.
2211 void FreeUnmarkedObjects();
2212
2213 // Checks whether a heap object is in this space; O(1).
2214 bool Contains(HeapObject* obj);
2215
2216 // Checks whether the space is empty.
2217 bool IsEmpty() { return first_chunk_ == NULL; }
2218
Leon Clarkee46be812010-01-19 14:06:41 +00002219 // See the comments for ReserveSpace in the Space class. This has to be
2220 // called after ReserveSpace has been called on the paged spaces, since they
2221 // may use some memory, leaving less for large objects.
2222 virtual bool ReserveSpace(int bytes);
2223
Steve Blocka7e24c12009-10-30 11:49:00 +00002224#ifdef ENABLE_HEAP_PROTECTION
2225 // Protect/unprotect the space by marking it read-only/writable.
2226 void Protect();
2227 void Unprotect();
2228#endif
2229
2230#ifdef DEBUG
2231 virtual void Verify();
2232 virtual void Print();
2233 void ReportStatistics();
2234 void CollectCodeStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00002235#endif
2236 // Checks whether an address is in the object area in this space. It
2237 // iterates all objects in the space. May be slow.
2238 bool SlowContains(Address addr) { return !FindObject(addr)->IsFailure(); }
2239
2240 private:
2241 // The head of the linked list of large object chunks.
2242 LargeObjectChunk* first_chunk_;
Ben Murdochf87a2032010-10-22 12:50:53 +01002243 intptr_t size_; // allocated bytes
Steve Blocka7e24c12009-10-30 11:49:00 +00002244 int page_count_; // number of chunks
2245
2246
2247 // Shared implementation of AllocateRaw, AllocateRawCode and
2248 // AllocateRawFixedArray.
John Reck59135872010-11-02 12:39:01 -07002249 MUST_USE_RESULT MaybeObject* AllocateRawInternal(int requested_size,
2250 int object_size,
2251 Executability executable);
Steve Blocka7e24c12009-10-30 11:49:00 +00002252
Steve Blocka7e24c12009-10-30 11:49:00 +00002253 friend class LargeObjectIterator;
2254
2255 public:
2256 TRACK_MEMORY("LargeObjectSpace")
2257};
2258
2259
2260class LargeObjectIterator: public ObjectIterator {
2261 public:
2262 explicit LargeObjectIterator(LargeObjectSpace* space);
2263 LargeObjectIterator(LargeObjectSpace* space, HeapObjectCallback size_func);
2264
Steve Blocka7e24c12009-10-30 11:49:00 +00002265 HeapObject* next();
2266
2267 // implementation of ObjectIterator.
Steve Blocka7e24c12009-10-30 11:49:00 +00002268 virtual HeapObject* next_object() { return next(); }
2269
2270 private:
2271 LargeObjectChunk* current_;
2272 HeapObjectCallback size_func_;
2273};
2274
2275
2276} } // namespace v8::internal
2277
2278#endif // V8_SPACES_H_