blob: a6b8ea48df3b7fc17cf4810d9dd0744007c3fe2d [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
246 // The start offset of the object area in a page.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100247 static const int kObjectStartOffset = MAP_POINTER_ALIGN(kPageHeaderSize);
Steve Blocka7e24c12009-10-30 11:49:00 +0000248
249 // Object area size in bytes.
250 static const int kObjectAreaSize = kPageSize - kObjectStartOffset;
251
252 // Maximum object size that fits in a page.
253 static const int kMaxHeapObjectSize = kObjectAreaSize;
254
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100255 static const int kDirtyFlagOffset = 2 * kPointerSize;
256 static const int kRegionSizeLog2 = 8;
257 static const int kRegionSize = 1 << kRegionSizeLog2;
258 static const intptr_t kRegionAlignmentMask = (kRegionSize - 1);
259
260 STATIC_CHECK(kRegionSize == kPageSize / kBitsPerInt);
261
Steve Block6ded16b2010-05-10 14:33:55 +0100262 enum PageFlag {
Steve Block791712a2010-08-27 10:21:07 +0100263 IS_NORMAL_PAGE = 0,
264 WAS_IN_USE_BEFORE_MC,
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100265
266 // Page allocation watermark was bumped by preallocation during scavenge.
267 // Correct watermark can be retrieved by CachedAllocationWatermark() method
Steve Block791712a2010-08-27 10:21:07 +0100268 WATERMARK_INVALIDATED,
269 IS_EXECUTABLE,
270 NUM_PAGE_FLAGS // Must be last
Steve Block6ded16b2010-05-10 14:33:55 +0100271 };
Steve Block791712a2010-08-27 10:21:07 +0100272 static const int kPageFlagMask = (1 << NUM_PAGE_FLAGS) - 1;
Steve Block6ded16b2010-05-10 14:33:55 +0100273
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100274 // To avoid an additional WATERMARK_INVALIDATED flag clearing pass during
275 // scavenge we just invalidate the watermark on each old space page after
276 // processing it. And then we flip the meaning of the WATERMARK_INVALIDATED
277 // flag at the beginning of the next scavenge and each page becomes marked as
278 // having a valid watermark.
279 //
280 // The following invariant must hold for pages in old pointer and map spaces:
281 // If page is in use then page is marked as having invalid watermark at
282 // the beginning and at the end of any GC.
283 //
284 // This invariant guarantees that after flipping flag meaning at the
285 // beginning of scavenge all pages in use will be marked as having valid
286 // watermark.
287 static inline void FlipMeaningOfInvalidatedWatermarkFlag();
288
289 // Returns true if the page allocation watermark was not altered during
290 // scavenge.
291 inline bool IsWatermarkValid();
292
293 inline void InvalidateWatermark(bool value);
294
Steve Block6ded16b2010-05-10 14:33:55 +0100295 inline bool GetPageFlag(PageFlag flag);
296 inline void SetPageFlag(PageFlag flag, bool value);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100297 inline void ClearPageFlags();
298
299 inline void ClearGCFields();
300
Steve Block791712a2010-08-27 10:21:07 +0100301 static const int kAllocationWatermarkOffsetShift = WATERMARK_INVALIDATED + 1;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100302 static const int kAllocationWatermarkOffsetBits = kPageSizeBits + 1;
303 static const uint32_t kAllocationWatermarkOffsetMask =
304 ((1 << kAllocationWatermarkOffsetBits) - 1) <<
305 kAllocationWatermarkOffsetShift;
306
307 static const uint32_t kFlagsMask =
308 ((1 << kAllocationWatermarkOffsetShift) - 1);
309
310 STATIC_CHECK(kBitsPerInt - kAllocationWatermarkOffsetShift >=
311 kAllocationWatermarkOffsetBits);
312
313 // This field contains the meaning of the WATERMARK_INVALIDATED flag.
314 // Instead of clearing this flag from all pages we just flip
315 // its meaning at the beginning of a scavenge.
316 static intptr_t watermark_invalidated_mark_;
Steve Block6ded16b2010-05-10 14:33:55 +0100317
Steve Blocka7e24c12009-10-30 11:49:00 +0000318 //---------------------------------------------------------------------------
319 // Page header description.
320 //
321 // If a page is not in the large object space, the first word,
322 // opaque_header, encodes the next page address (aligned to kPageSize 8K)
323 // and the chunk number (0 ~ 8K-1). Only MemoryAllocator should use
324 // opaque_header. The value range of the opaque_header is [0..kPageSize[,
325 // or [next_page_start, next_page_end[. It cannot point to a valid address
326 // in the current page. If a page is in the large object space, the first
327 // word *may* (if the page start and large object chunk start are the
328 // same) contain the address of the next large object chunk.
329 intptr_t opaque_header;
330
331 // If the page is not in the large object space, the low-order bit of the
332 // second word is set. If the page is in the large object space, the
333 // second word *may* (if the page start and large object chunk start are
334 // the same) contain the large object chunk size. In either case, the
335 // low-order bit for large object pages will be cleared.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100336 // For normal pages this word is used to store page flags and
337 // offset of allocation top.
338 intptr_t flags_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000339
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100340 // This field contains dirty marks for regions covering the page. Only dirty
341 // regions might contain intergenerational references.
342 // Only 32 dirty marks are supported so for large object pages several regions
343 // might be mapped to a single dirty mark.
344 uint32_t dirty_regions_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000345
346 // The index of the page in its owner space.
347 int mc_page_index;
348
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100349 // During mark-compact collections this field contains the forwarding address
350 // of the first live object in this page.
351 // During scavenge collection this field is used to store allocation watermark
352 // if it is altered during scavenge.
Steve Blocka7e24c12009-10-30 11:49:00 +0000353 Address mc_first_forwarded;
Steve Blocka7e24c12009-10-30 11:49:00 +0000354};
355
356
357// ----------------------------------------------------------------------------
358// Space is the abstract superclass for all allocation spaces.
359class Space : public Malloced {
360 public:
361 Space(AllocationSpace id, Executability executable)
362 : id_(id), executable_(executable) {}
363
364 virtual ~Space() {}
365
366 // Does the space need executable memory?
367 Executability executable() { return executable_; }
368
369 // Identity used in error reporting.
370 AllocationSpace identity() { return id_; }
371
372 virtual int Size() = 0;
373
Steve Block6ded16b2010-05-10 14:33:55 +0100374#ifdef ENABLE_HEAP_PROTECTION
375 // Protect/unprotect the space by marking it read-only/writable.
376 virtual void Protect() = 0;
377 virtual void Unprotect() = 0;
378#endif
379
Steve Blocka7e24c12009-10-30 11:49:00 +0000380#ifdef DEBUG
381 virtual void Print() = 0;
382#endif
383
Leon Clarkee46be812010-01-19 14:06:41 +0000384 // After calling this we can allocate a certain number of bytes using only
385 // linear allocation (with a LinearAllocationScope and an AlwaysAllocateScope)
386 // without using freelists or causing a GC. This is used by partial
387 // snapshots. It returns true of space was reserved or false if a GC is
388 // needed. For paged spaces the space requested must include the space wasted
389 // at the end of each when allocating linearly.
390 virtual bool ReserveSpace(int bytes) = 0;
391
Steve Blocka7e24c12009-10-30 11:49:00 +0000392 private:
393 AllocationSpace id_;
394 Executability executable_;
395};
396
397
398// ----------------------------------------------------------------------------
399// All heap objects containing executable code (code objects) must be allocated
400// from a 2 GB range of memory, so that they can call each other using 32-bit
401// displacements. This happens automatically on 32-bit platforms, where 32-bit
402// displacements cover the entire 4GB virtual address space. On 64-bit
403// platforms, we support this using the CodeRange object, which reserves and
404// manages a range of virtual memory.
405class CodeRange : public AllStatic {
406 public:
407 // Reserves a range of virtual memory, but does not commit any of it.
408 // Can only be called once, at heap initialization time.
409 // Returns false on failure.
410 static bool Setup(const size_t requested_size);
411
412 // Frees the range of virtual memory, and frees the data structures used to
413 // manage it.
414 static void TearDown();
415
416 static bool exists() { return code_range_ != NULL; }
417 static bool contains(Address address) {
418 if (code_range_ == NULL) return false;
419 Address start = static_cast<Address>(code_range_->address());
420 return start <= address && address < start + code_range_->size();
421 }
422
423 // Allocates a chunk of memory from the large-object portion of
424 // the code range. On platforms with no separate code range, should
425 // not be called.
426 static void* AllocateRawMemory(const size_t requested, size_t* allocated);
427 static void FreeRawMemory(void* buf, size_t length);
428
429 private:
430 // The reserved range of virtual memory that all code objects are put in.
431 static VirtualMemory* code_range_;
432 // Plain old data class, just a struct plus a constructor.
433 class FreeBlock {
434 public:
435 FreeBlock(Address start_arg, size_t size_arg)
436 : start(start_arg), size(size_arg) {}
437 FreeBlock(void* start_arg, size_t size_arg)
438 : start(static_cast<Address>(start_arg)), size(size_arg) {}
439
440 Address start;
441 size_t size;
442 };
443
444 // Freed blocks of memory are added to the free list. When the allocation
445 // list is exhausted, the free list is sorted and merged to make the new
446 // allocation list.
447 static List<FreeBlock> free_list_;
448 // Memory is allocated from the free blocks on the allocation list.
449 // The block at current_allocation_block_index_ is the current block.
450 static List<FreeBlock> allocation_list_;
451 static int current_allocation_block_index_;
452
453 // Finds a block on the allocation list that contains at least the
454 // requested amount of memory. If none is found, sorts and merges
455 // the existing free memory blocks, and searches again.
456 // If none can be found, terminates V8 with FatalProcessOutOfMemory.
457 static void GetNextAllocationBlock(size_t requested);
458 // Compares the start addresses of two free blocks.
459 static int CompareFreeBlockAddress(const FreeBlock* left,
460 const FreeBlock* right);
461};
462
463
464// ----------------------------------------------------------------------------
465// A space acquires chunks of memory from the operating system. The memory
466// allocator manages chunks for the paged heap spaces (old space and map
467// space). A paged chunk consists of pages. Pages in a chunk have contiguous
468// addresses and are linked as a list.
469//
470// The allocator keeps an initial chunk which is used for the new space. The
471// leftover regions of the initial chunk are used for the initial chunks of
472// old space and map space if they are big enough to hold at least one page.
473// The allocator assumes that there is one old space and one map space, each
474// expands the space by allocating kPagesPerChunk pages except the last
475// expansion (before running out of space). The first chunk may contain fewer
476// than kPagesPerChunk pages as well.
477//
478// The memory allocator also allocates chunks for the large object space, but
479// they are managed by the space itself. The new space does not expand.
Steve Block6ded16b2010-05-10 14:33:55 +0100480//
481// The fact that pages for paged spaces are allocated and deallocated in chunks
482// induces a constraint on the order of pages in a linked lists. We say that
483// pages are linked in the chunk-order if and only if every two consecutive
484// pages from the same chunk are consecutive in the linked list.
485//
486
Steve Blocka7e24c12009-10-30 11:49:00 +0000487
488class MemoryAllocator : public AllStatic {
489 public:
490 // Initializes its internal bookkeeping structures.
491 // Max capacity of the total space.
492 static bool Setup(int max_capacity);
493
494 // Deletes valid chunks.
495 static void TearDown();
496
497 // Reserves an initial address range of virtual memory to be split between
498 // the two new space semispaces, the old space, and the map space. The
499 // memory is not yet committed or assigned to spaces and split into pages.
500 // The initial chunk is unmapped when the memory allocator is torn down.
501 // This function should only be called when there is not already a reserved
502 // initial chunk (initial_chunk_ should be NULL). It returns the start
503 // address of the initial chunk if successful, with the side effect of
504 // setting the initial chunk, or else NULL if unsuccessful and leaves the
505 // initial chunk NULL.
506 static void* ReserveInitialChunk(const size_t requested);
507
508 // Commits pages from an as-yet-unmanaged block of virtual memory into a
509 // paged space. The block should be part of the initial chunk reserved via
510 // a call to ReserveInitialChunk. The number of pages is always returned in
511 // the output parameter num_pages. This function assumes that the start
512 // address is non-null and that it is big enough to hold at least one
513 // page-aligned page. The call always succeeds, and num_pages is always
514 // greater than zero.
515 static Page* CommitPages(Address start, size_t size, PagedSpace* owner,
516 int* num_pages);
517
518 // Commit a contiguous block of memory from the initial chunk. Assumes that
519 // the address is not NULL, the size is greater than zero, and that the
520 // block is contained in the initial chunk. Returns true if it succeeded
521 // and false otherwise.
522 static bool CommitBlock(Address start, size_t size, Executability executable);
523
Steve Blocka7e24c12009-10-30 11:49:00 +0000524 // Uncommit a contiguous block of memory [start..(start+size)[.
525 // start is not NULL, the size is greater than zero, and the
526 // block is contained in the initial chunk. Returns true if it succeeded
527 // and false otherwise.
528 static bool UncommitBlock(Address start, size_t size);
529
Leon Clarke4515c472010-02-03 11:58:03 +0000530 // Zaps a contiguous block of memory [start..(start+size)[ thus
531 // filling it up with a recognizable non-NULL bit pattern.
532 static void ZapBlock(Address start, size_t size);
533
Steve Blocka7e24c12009-10-30 11:49:00 +0000534 // Attempts to allocate the requested (non-zero) number of pages from the
535 // OS. Fewer pages might be allocated than requested. If it fails to
536 // allocate memory for the OS or cannot allocate a single page, this
537 // function returns an invalid page pointer (NULL). The caller must check
538 // whether the returned page is valid (by calling Page::is_valid()). It is
539 // guaranteed that allocated pages have contiguous addresses. The actual
540 // number of allocated pages is returned in the output parameter
541 // allocated_pages. If the PagedSpace owner is executable and there is
542 // a code range, the pages are allocated from the code range.
543 static Page* AllocatePages(int requested_pages, int* allocated_pages,
544 PagedSpace* owner);
545
Steve Block6ded16b2010-05-10 14:33:55 +0100546 // Frees pages from a given page and after. Requires pages to be
547 // linked in chunk-order (see comment for class).
548 // If 'p' is the first page of a chunk, pages from 'p' are freed
549 // and this function returns an invalid page pointer.
550 // Otherwise, the function searches a page after 'p' that is
551 // the first page of a chunk. Pages after the found page
552 // are freed and the function returns 'p'.
Steve Blocka7e24c12009-10-30 11:49:00 +0000553 static Page* FreePages(Page* p);
554
Steve Block6ded16b2010-05-10 14:33:55 +0100555 // Frees all pages owned by given space.
556 static void FreeAllPages(PagedSpace* space);
557
Steve Blocka7e24c12009-10-30 11:49:00 +0000558 // Allocates and frees raw memory of certain size.
559 // These are just thin wrappers around OS::Allocate and OS::Free,
560 // but keep track of allocated bytes as part of heap.
561 // If the flag is EXECUTABLE and a code range exists, the requested
562 // memory is allocated from the code range. If a code range exists
563 // and the freed memory is in it, the code range manages the freed memory.
564 static void* AllocateRawMemory(const size_t requested,
565 size_t* allocated,
566 Executability executable);
Steve Block791712a2010-08-27 10:21:07 +0100567 static void FreeRawMemory(void* buf,
568 size_t length,
569 Executability executable);
Steve Blocka7e24c12009-10-30 11:49:00 +0000570
571 // Returns the maximum available bytes of heaps.
572 static int Available() { return capacity_ < size_ ? 0 : capacity_ - size_; }
573
574 // Returns allocated spaces in bytes.
575 static int Size() { return size_; }
576
Steve Block791712a2010-08-27 10:21:07 +0100577 // Returns allocated executable spaces in bytes.
578 static int SizeExecutable() { return size_executable_; }
579
Steve Blocka7e24c12009-10-30 11:49:00 +0000580 // Returns maximum available bytes that the old space can have.
581 static int MaxAvailable() {
582 return (Available() / Page::kPageSize) * Page::kObjectAreaSize;
583 }
584
585 // Links two pages.
586 static inline void SetNextPage(Page* prev, Page* next);
587
588 // Returns the next page of a given page.
589 static inline Page* GetNextPage(Page* p);
590
591 // Checks whether a page belongs to a space.
592 static inline bool IsPageInSpace(Page* p, PagedSpace* space);
593
594 // Returns the space that owns the given page.
595 static inline PagedSpace* PageOwner(Page* page);
596
597 // Finds the first/last page in the same chunk as a given page.
598 static Page* FindFirstPageInSameChunk(Page* p);
599 static Page* FindLastPageInSameChunk(Page* p);
600
Steve Block6ded16b2010-05-10 14:33:55 +0100601 // Relinks list of pages owned by space to make it chunk-ordered.
602 // Returns new first and last pages of space.
603 // Also returns last page in relinked list which has WasInUsedBeforeMC
604 // flag set.
605 static void RelinkPageListInChunkOrder(PagedSpace* space,
606 Page** first_page,
607 Page** last_page,
608 Page** last_page_in_use);
609
Steve Blocka7e24c12009-10-30 11:49:00 +0000610#ifdef ENABLE_HEAP_PROTECTION
611 // Protect/unprotect a block of memory by marking it read-only/writable.
612 static inline void Protect(Address start, size_t size);
613 static inline void Unprotect(Address start, size_t size,
614 Executability executable);
615
616 // Protect/unprotect a chunk given a page in the chunk.
617 static inline void ProtectChunkFromPage(Page* page);
618 static inline void UnprotectChunkFromPage(Page* page);
619#endif
620
621#ifdef DEBUG
622 // Reports statistic info of the space.
623 static void ReportStatistics();
624#endif
625
626 // Due to encoding limitation, we can only have 8K chunks.
Leon Clarkee46be812010-01-19 14:06:41 +0000627 static const int kMaxNofChunks = 1 << kPageSizeBits;
Steve Blocka7e24c12009-10-30 11:49:00 +0000628 // If a chunk has at least 16 pages, the maximum heap size is about
629 // 8K * 8K * 16 = 1G bytes.
630#ifdef V8_TARGET_ARCH_X64
631 static const int kPagesPerChunk = 32;
632#else
633 static const int kPagesPerChunk = 16;
634#endif
635 static const int kChunkSize = kPagesPerChunk * Page::kPageSize;
636
637 private:
638 // Maximum space size in bytes.
639 static int capacity_;
640
641 // Allocated space size in bytes.
642 static int size_;
Steve Block791712a2010-08-27 10:21:07 +0100643 // Allocated executable space size in bytes.
644 static int size_executable_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000645
646 // The initial chunk of virtual memory.
647 static VirtualMemory* initial_chunk_;
648
649 // Allocated chunk info: chunk start address, chunk size, and owning space.
650 class ChunkInfo BASE_EMBEDDED {
651 public:
652 ChunkInfo() : address_(NULL), size_(0), owner_(NULL) {}
653 void init(Address a, size_t s, PagedSpace* o) {
654 address_ = a;
655 size_ = s;
656 owner_ = o;
657 }
658 Address address() { return address_; }
659 size_t size() { return size_; }
660 PagedSpace* owner() { return owner_; }
661
662 private:
663 Address address_;
664 size_t size_;
665 PagedSpace* owner_;
666 };
667
668 // Chunks_, free_chunk_ids_ and top_ act as a stack of free chunk ids.
669 static List<ChunkInfo> chunks_;
670 static List<int> free_chunk_ids_;
671 static int max_nof_chunks_;
672 static int top_;
673
674 // Push/pop a free chunk id onto/from the stack.
675 static void Push(int free_chunk_id);
676 static int Pop();
677 static bool OutOfChunkIds() { return top_ == 0; }
678
679 // Frees a chunk.
680 static void DeleteChunk(int chunk_id);
681
682 // Basic check whether a chunk id is in the valid range.
683 static inline bool IsValidChunkId(int chunk_id);
684
685 // Checks whether a chunk id identifies an allocated chunk.
686 static inline bool IsValidChunk(int chunk_id);
687
688 // Returns the chunk id that a page belongs to.
689 static inline int GetChunkId(Page* p);
690
691 // True if the address lies in the initial chunk.
692 static inline bool InInitialChunk(Address address);
693
694 // Initializes pages in a chunk. Returns the first page address.
695 // This function and GetChunkId() are provided for the mark-compact
696 // collector to rebuild page headers in the from space, which is
697 // used as a marking stack and its page headers are destroyed.
698 static Page* InitializePagesInChunk(int chunk_id, int pages_in_chunk,
699 PagedSpace* owner);
Steve Block6ded16b2010-05-10 14:33:55 +0100700
701 static Page* RelinkPagesInChunk(int chunk_id,
702 Address chunk_start,
703 size_t chunk_size,
704 Page* prev,
705 Page** last_page_in_use);
Steve Blocka7e24c12009-10-30 11:49:00 +0000706};
707
708
709// -----------------------------------------------------------------------------
710// Interface for heap object iterator to be implemented by all object space
711// object iterators.
712//
Leon Clarked91b9f72010-01-27 17:25:45 +0000713// NOTE: The space specific object iterators also implements the own next()
714// method which is used to avoid using virtual functions
Steve Blocka7e24c12009-10-30 11:49:00 +0000715// iterating a specific space.
716
717class ObjectIterator : public Malloced {
718 public:
719 virtual ~ObjectIterator() { }
720
Steve Blocka7e24c12009-10-30 11:49:00 +0000721 virtual HeapObject* next_object() = 0;
722};
723
724
725// -----------------------------------------------------------------------------
726// Heap object iterator in new/old/map spaces.
727//
728// A HeapObjectIterator iterates objects from a given address to the
729// top of a space. The given address must be below the current
730// allocation pointer (space top). There are some caveats.
731//
732// (1) If the space top changes upward during iteration (because of
733// allocating new objects), the iterator does not iterate objects
734// above the original space top. The caller must create a new
735// iterator starting from the old top in order to visit these new
736// objects.
737//
738// (2) If new objects are allocated below the original allocation top
739// (e.g., free-list allocation in paged spaces), the new objects
740// may or may not be iterated depending on their position with
741// respect to the current point of iteration.
742//
743// (3) The space top should not change downward during iteration,
744// otherwise the iterator will return not-necessarily-valid
745// objects.
746
747class HeapObjectIterator: public ObjectIterator {
748 public:
749 // Creates a new object iterator in a given space. If a start
750 // address is not given, the iterator starts from the space bottom.
751 // If the size function is not given, the iterator calls the default
752 // Object::Size().
753 explicit HeapObjectIterator(PagedSpace* space);
754 HeapObjectIterator(PagedSpace* space, HeapObjectCallback size_func);
755 HeapObjectIterator(PagedSpace* space, Address start);
756 HeapObjectIterator(PagedSpace* space,
757 Address start,
758 HeapObjectCallback size_func);
759
Leon Clarked91b9f72010-01-27 17:25:45 +0000760 inline HeapObject* next() {
761 return (cur_addr_ < cur_limit_) ? FromCurrentPage() : FromNextPage();
762 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000763
764 // implementation of ObjectIterator.
Steve Blocka7e24c12009-10-30 11:49:00 +0000765 virtual HeapObject* next_object() { return next(); }
766
767 private:
768 Address cur_addr_; // current iteration point
769 Address end_addr_; // end iteration point
770 Address cur_limit_; // current page limit
771 HeapObjectCallback size_func_; // size function
772 Page* end_page_; // caches the page of the end address
773
Leon Clarked91b9f72010-01-27 17:25:45 +0000774 HeapObject* FromCurrentPage() {
775 ASSERT(cur_addr_ < cur_limit_);
776
777 HeapObject* obj = HeapObject::FromAddress(cur_addr_);
778 int obj_size = (size_func_ == NULL) ? obj->Size() : size_func_(obj);
779 ASSERT_OBJECT_SIZE(obj_size);
780
781 cur_addr_ += obj_size;
782 ASSERT(cur_addr_ <= cur_limit_);
783
784 return obj;
785 }
786
787 // Slow path of next, goes into the next page.
788 HeapObject* FromNextPage();
Steve Blocka7e24c12009-10-30 11:49:00 +0000789
790 // Initializes fields.
791 void Initialize(Address start, Address end, HeapObjectCallback size_func);
792
793#ifdef DEBUG
794 // Verifies whether fields have valid values.
795 void Verify();
796#endif
797};
798
799
800// -----------------------------------------------------------------------------
801// A PageIterator iterates the pages in a paged space.
802//
803// The PageIterator class provides three modes for iterating pages in a space:
804// PAGES_IN_USE iterates pages containing allocated objects.
805// PAGES_USED_BY_MC iterates pages that hold relocated objects during a
806// mark-compact collection.
807// ALL_PAGES iterates all pages in the space.
808//
809// There are some caveats.
810//
811// (1) If the space expands during iteration, new pages will not be
812// returned by the iterator in any mode.
813//
814// (2) If new objects are allocated during iteration, they will appear
815// in pages returned by the iterator. Allocation may cause the
816// allocation pointer or MC allocation pointer in the last page to
817// change between constructing the iterator and iterating the last
818// page.
819//
820// (3) The space should not shrink during iteration, otherwise the
821// iterator will return deallocated pages.
822
823class PageIterator BASE_EMBEDDED {
824 public:
825 enum Mode {
826 PAGES_IN_USE,
827 PAGES_USED_BY_MC,
828 ALL_PAGES
829 };
830
831 PageIterator(PagedSpace* space, Mode mode);
832
833 inline bool has_next();
834 inline Page* next();
835
836 private:
837 PagedSpace* space_;
838 Page* prev_page_; // Previous page returned.
839 Page* stop_page_; // Page to stop at (last page returned by the iterator).
840};
841
842
843// -----------------------------------------------------------------------------
844// A space has a list of pages. The next page can be accessed via
845// Page::next_page() call. The next page of the last page is an
846// invalid page pointer. A space can expand and shrink dynamically.
847
848// An abstraction of allocation and relocation pointers in a page-structured
849// space.
850class AllocationInfo {
851 public:
852 Address top; // current allocation top
853 Address limit; // current allocation limit
854
855#ifdef DEBUG
856 bool VerifyPagedAllocation() {
857 return (Page::FromAllocationTop(top) == Page::FromAllocationTop(limit))
858 && (top <= limit);
859 }
860#endif
861};
862
863
864// An abstraction of the accounting statistics of a page-structured space.
865// The 'capacity' of a space is the number of object-area bytes (ie, not
866// including page bookkeeping structures) currently in the space. The 'size'
867// of a space is the number of allocated bytes, the 'waste' in the space is
868// the number of bytes that are not allocated and not available to
869// allocation without reorganizing the space via a GC (eg, small blocks due
870// to internal fragmentation, top of page areas in map space), and the bytes
871// 'available' is the number of unallocated bytes that are not waste. The
872// capacity is the sum of size, waste, and available.
873//
874// The stats are only set by functions that ensure they stay balanced. These
875// functions increase or decrease one of the non-capacity stats in
876// conjunction with capacity, or else they always balance increases and
877// decreases to the non-capacity stats.
878class AllocationStats BASE_EMBEDDED {
879 public:
880 AllocationStats() { Clear(); }
881
882 // Zero out all the allocation statistics (ie, no capacity).
883 void Clear() {
884 capacity_ = 0;
885 available_ = 0;
886 size_ = 0;
887 waste_ = 0;
888 }
889
890 // Reset the allocation statistics (ie, available = capacity with no
891 // wasted or allocated bytes).
892 void Reset() {
893 available_ = capacity_;
894 size_ = 0;
895 waste_ = 0;
896 }
897
898 // Accessors for the allocation statistics.
899 int Capacity() { return capacity_; }
900 int Available() { return available_; }
901 int Size() { return size_; }
902 int Waste() { return waste_; }
903
904 // Grow the space by adding available bytes.
905 void ExpandSpace(int size_in_bytes) {
906 capacity_ += size_in_bytes;
907 available_ += size_in_bytes;
908 }
909
910 // Shrink the space by removing available bytes.
911 void ShrinkSpace(int size_in_bytes) {
912 capacity_ -= size_in_bytes;
913 available_ -= size_in_bytes;
914 }
915
916 // Allocate from available bytes (available -> size).
917 void AllocateBytes(int size_in_bytes) {
918 available_ -= size_in_bytes;
919 size_ += size_in_bytes;
920 }
921
922 // Free allocated bytes, making them available (size -> available).
923 void DeallocateBytes(int size_in_bytes) {
924 size_ -= size_in_bytes;
925 available_ += size_in_bytes;
926 }
927
928 // Waste free bytes (available -> waste).
929 void WasteBytes(int size_in_bytes) {
930 available_ -= size_in_bytes;
931 waste_ += size_in_bytes;
932 }
933
934 // Consider the wasted bytes to be allocated, as they contain filler
935 // objects (waste -> size).
936 void FillWastedBytes(int size_in_bytes) {
937 waste_ -= size_in_bytes;
938 size_ += size_in_bytes;
939 }
940
941 private:
942 int capacity_;
943 int available_;
944 int size_;
945 int waste_;
946};
947
948
949class PagedSpace : public Space {
950 public:
951 // Creates a space with a maximum capacity, and an id.
952 PagedSpace(int max_capacity, AllocationSpace id, Executability executable);
953
954 virtual ~PagedSpace() {}
955
956 // Set up the space using the given address range of virtual memory (from
957 // the memory allocator's initial chunk) if possible. If the block of
958 // addresses is not big enough to contain a single page-aligned page, a
959 // fresh chunk will be allocated.
960 bool Setup(Address start, size_t size);
961
962 // Returns true if the space has been successfully set up and not
963 // subsequently torn down.
964 bool HasBeenSetup();
965
966 // Cleans up the space, frees all pages in this space except those belonging
967 // to the initial chunk, uncommits addresses in the initial chunk.
968 void TearDown();
969
970 // Checks whether an object/address is in this space.
971 inline bool Contains(Address a);
972 bool Contains(HeapObject* o) { return Contains(o->address()); }
973
974 // Given an address occupied by a live object, return that object if it is
975 // in this space, or Failure::Exception() if it is not. The implementation
976 // iterates over objects in the page containing the address, the cost is
977 // linear in the number of objects in the page. It may be slow.
978 Object* FindObject(Address addr);
979
980 // Checks whether page is currently in use by this space.
981 bool IsUsed(Page* page);
982
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100983 void MarkAllPagesClean();
Steve Blocka7e24c12009-10-30 11:49:00 +0000984
985 // Prepares for a mark-compact GC.
Steve Block6ded16b2010-05-10 14:33:55 +0100986 virtual void PrepareForMarkCompact(bool will_compact);
Steve Blocka7e24c12009-10-30 11:49:00 +0000987
Steve Block6ded16b2010-05-10 14:33:55 +0100988 // The top of allocation in a page in this space. Undefined if page is unused.
989 Address PageAllocationTop(Page* page) {
990 return page == TopPageOf(allocation_info_) ? top()
991 : PageAllocationLimit(page);
992 }
993
994 // The limit of allocation for a page in this space.
995 virtual Address PageAllocationLimit(Page* page) = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000996
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100997 void FlushTopPageWatermark() {
998 AllocationTopPage()->SetCachedAllocationWatermark(top());
999 AllocationTopPage()->InvalidateWatermark(true);
1000 }
1001
Steve Blocka7e24c12009-10-30 11:49:00 +00001002 // Current capacity without growing (Size() + Available() + Waste()).
1003 int Capacity() { return accounting_stats_.Capacity(); }
1004
Steve Block3ce2e202009-11-05 08:53:23 +00001005 // Total amount of memory committed for this space. For paged
1006 // spaces this equals the capacity.
1007 int CommittedMemory() { return Capacity(); }
1008
Steve Blocka7e24c12009-10-30 11:49:00 +00001009 // Available bytes without growing.
1010 int Available() { return accounting_stats_.Available(); }
1011
1012 // Allocated bytes in this space.
1013 virtual int Size() { return accounting_stats_.Size(); }
1014
1015 // Wasted bytes due to fragmentation and not recoverable until the
1016 // next GC of this space.
1017 int Waste() { return accounting_stats_.Waste(); }
1018
1019 // Returns the address of the first object in this space.
1020 Address bottom() { return first_page_->ObjectAreaStart(); }
1021
1022 // Returns the allocation pointer in this space.
1023 Address top() { return allocation_info_.top; }
1024
1025 // Allocate the requested number of bytes in the space if possible, return a
1026 // failure object if not.
1027 inline Object* AllocateRaw(int size_in_bytes);
1028
1029 // Allocate the requested number of bytes for relocation during mark-compact
1030 // collection.
1031 inline Object* MCAllocateRaw(int size_in_bytes);
1032
Leon Clarkee46be812010-01-19 14:06:41 +00001033 virtual bool ReserveSpace(int bytes);
1034
1035 // Used by ReserveSpace.
1036 virtual void PutRestOfCurrentPageOnFreeList(Page* current_page) = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00001037
Steve Block6ded16b2010-05-10 14:33:55 +01001038 // Free all pages in range from prev (exclusive) to last (inclusive).
1039 // Freed pages are moved to the end of page list.
1040 void FreePages(Page* prev, Page* last);
1041
1042 // Set space allocation info.
1043 void SetTop(Address top) {
1044 allocation_info_.top = top;
1045 allocation_info_.limit = PageAllocationLimit(Page::FromAllocationTop(top));
1046 }
1047
Steve Blocka7e24c12009-10-30 11:49:00 +00001048 // ---------------------------------------------------------------------------
1049 // Mark-compact collection support functions
1050
1051 // Set the relocation point to the beginning of the space.
1052 void MCResetRelocationInfo();
1053
1054 // Writes relocation info to the top page.
1055 void MCWriteRelocationInfoToPage() {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001056 TopPageOf(mc_forwarding_info_)->
1057 SetAllocationWatermark(mc_forwarding_info_.top);
Steve Blocka7e24c12009-10-30 11:49:00 +00001058 }
1059
1060 // Computes the offset of a given address in this space to the beginning
1061 // of the space.
1062 int MCSpaceOffsetForAddress(Address addr);
1063
1064 // Updates the allocation pointer to the relocation top after a mark-compact
1065 // collection.
1066 virtual void MCCommitRelocationInfo() = 0;
1067
1068 // Releases half of unused pages.
1069 void Shrink();
1070
1071 // Ensures that the capacity is at least 'capacity'. Returns false on failure.
1072 bool EnsureCapacity(int capacity);
1073
1074#ifdef ENABLE_HEAP_PROTECTION
1075 // Protect/unprotect the space by marking it read-only/writable.
1076 void Protect();
1077 void Unprotect();
1078#endif
1079
1080#ifdef DEBUG
1081 // Print meta info and objects in this space.
1082 virtual void Print();
1083
1084 // Verify integrity of this space.
1085 virtual void Verify(ObjectVisitor* visitor);
1086
1087 // Overridden by subclasses to verify space-specific object
1088 // properties (e.g., only maps or free-list nodes are in map space).
1089 virtual void VerifyObject(HeapObject* obj) {}
1090
1091 // Report code object related statistics
1092 void CollectCodeStatistics();
1093 static void ReportCodeStatistics();
1094 static void ResetCodeStatistics();
1095#endif
1096
Steve Block6ded16b2010-05-10 14:33:55 +01001097 // Returns the page of the allocation pointer.
1098 Page* AllocationTopPage() { return TopPageOf(allocation_info_); }
1099
Steve Blocka7e24c12009-10-30 11:49:00 +00001100 protected:
1101 // Maximum capacity of this space.
1102 int max_capacity_;
1103
1104 // Accounting information for this space.
1105 AllocationStats accounting_stats_;
1106
1107 // The first page in this space.
1108 Page* first_page_;
1109
1110 // The last page in this space. Initially set in Setup, updated in
1111 // Expand and Shrink.
1112 Page* last_page_;
1113
Steve Block6ded16b2010-05-10 14:33:55 +01001114 // True if pages owned by this space are linked in chunk-order.
1115 // See comment for class MemoryAllocator for definition of chunk-order.
1116 bool page_list_is_chunk_ordered_;
1117
Steve Blocka7e24c12009-10-30 11:49:00 +00001118 // Normal allocation information.
1119 AllocationInfo allocation_info_;
1120
1121 // Relocation information during mark-compact collections.
1122 AllocationInfo mc_forwarding_info_;
1123
1124 // Bytes of each page that cannot be allocated. Possibly non-zero
1125 // for pages in spaces with only fixed-size objects. Always zero
1126 // for pages in spaces with variable sized objects (those pages are
1127 // padded with free-list nodes).
1128 int page_extra_;
1129
1130 // Sets allocation pointer to a page bottom.
1131 static void SetAllocationInfo(AllocationInfo* alloc_info, Page* p);
1132
1133 // Returns the top page specified by an allocation info structure.
1134 static Page* TopPageOf(AllocationInfo alloc_info) {
1135 return Page::FromAllocationTop(alloc_info.limit);
1136 }
1137
Leon Clarked91b9f72010-01-27 17:25:45 +00001138 int CountPagesToTop() {
1139 Page* p = Page::FromAllocationTop(allocation_info_.top);
1140 PageIterator it(this, PageIterator::ALL_PAGES);
1141 int counter = 1;
1142 while (it.has_next()) {
1143 if (it.next() == p) return counter;
1144 counter++;
1145 }
1146 UNREACHABLE();
1147 return -1;
1148 }
1149
Steve Blocka7e24c12009-10-30 11:49:00 +00001150 // Expands the space by allocating a fixed number of pages. Returns false if
1151 // it cannot allocate requested number of pages from OS. Newly allocated
1152 // pages are append to the last_page;
1153 bool Expand(Page* last_page);
1154
1155 // Generic fast case allocation function that tries linear allocation in
1156 // the top page of 'alloc_info'. Returns NULL on failure.
1157 inline HeapObject* AllocateLinearly(AllocationInfo* alloc_info,
1158 int size_in_bytes);
1159
1160 // During normal allocation or deserialization, roll to the next page in
1161 // the space (there is assumed to be one) and allocate there. This
1162 // function is space-dependent.
1163 virtual HeapObject* AllocateInNextPage(Page* current_page,
1164 int size_in_bytes) = 0;
1165
1166 // Slow path of AllocateRaw. This function is space-dependent.
1167 virtual HeapObject* SlowAllocateRaw(int size_in_bytes) = 0;
1168
1169 // Slow path of MCAllocateRaw.
1170 HeapObject* SlowMCAllocateRaw(int size_in_bytes);
1171
1172#ifdef DEBUG
Leon Clarkee46be812010-01-19 14:06:41 +00001173 // Returns the number of total pages in this space.
1174 int CountTotalPages();
Steve Blocka7e24c12009-10-30 11:49:00 +00001175#endif
1176 private:
Steve Blocka7e24c12009-10-30 11:49:00 +00001177
1178 // Returns a pointer to the page of the relocation pointer.
1179 Page* MCRelocationTopPage() { return TopPageOf(mc_forwarding_info_); }
1180
Steve Blocka7e24c12009-10-30 11:49:00 +00001181 friend class PageIterator;
1182};
1183
1184
1185#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1186class NumberAndSizeInfo BASE_EMBEDDED {
1187 public:
1188 NumberAndSizeInfo() : number_(0), bytes_(0) {}
1189
1190 int number() const { return number_; }
1191 void increment_number(int num) { number_ += num; }
1192
1193 int bytes() const { return bytes_; }
1194 void increment_bytes(int size) { bytes_ += size; }
1195
1196 void clear() {
1197 number_ = 0;
1198 bytes_ = 0;
1199 }
1200
1201 private:
1202 int number_;
1203 int bytes_;
1204};
1205
1206
1207// HistogramInfo class for recording a single "bar" of a histogram. This
1208// class is used for collecting statistics to print to stdout (when compiled
1209// with DEBUG) or to the log file (when compiled with
1210// ENABLE_LOGGING_AND_PROFILING).
1211class HistogramInfo: public NumberAndSizeInfo {
1212 public:
1213 HistogramInfo() : NumberAndSizeInfo() {}
1214
1215 const char* name() { return name_; }
1216 void set_name(const char* name) { name_ = name; }
1217
1218 private:
1219 const char* name_;
1220};
1221#endif
1222
1223
1224// -----------------------------------------------------------------------------
1225// SemiSpace in young generation
1226//
1227// A semispace is a contiguous chunk of memory. The mark-compact collector
1228// uses the memory in the from space as a marking stack when tracing live
1229// objects.
1230
1231class SemiSpace : public Space {
1232 public:
1233 // Constructor.
1234 SemiSpace() :Space(NEW_SPACE, NOT_EXECUTABLE) {
1235 start_ = NULL;
1236 age_mark_ = NULL;
1237 }
1238
1239 // Sets up the semispace using the given chunk.
1240 bool Setup(Address start, int initial_capacity, int maximum_capacity);
1241
1242 // Tear down the space. Heap memory was not allocated by the space, so it
1243 // is not deallocated here.
1244 void TearDown();
1245
1246 // True if the space has been set up but not torn down.
1247 bool HasBeenSetup() { return start_ != NULL; }
1248
1249 // Grow the size of the semispace by committing extra virtual memory.
1250 // Assumes that the caller has checked that the semispace has not reached
1251 // its maximum capacity (and thus there is space available in the reserved
1252 // address range to grow).
1253 bool Grow();
1254
1255 // Grow the semispace to the new capacity. The new capacity
1256 // requested must be larger than the current capacity.
1257 bool GrowTo(int new_capacity);
1258
1259 // Shrinks the semispace to the new capacity. The new capacity
1260 // requested must be more than the amount of used memory in the
1261 // semispace and less than the current capacity.
1262 bool ShrinkTo(int new_capacity);
1263
1264 // Returns the start address of the space.
1265 Address low() { return start_; }
1266 // Returns one past the end address of the space.
1267 Address high() { return low() + capacity_; }
1268
1269 // Age mark accessors.
1270 Address age_mark() { return age_mark_; }
1271 void set_age_mark(Address mark) { age_mark_ = mark; }
1272
1273 // True if the address is in the address range of this semispace (not
1274 // necessarily below the allocation pointer).
1275 bool Contains(Address a) {
1276 return (reinterpret_cast<uintptr_t>(a) & address_mask_)
1277 == reinterpret_cast<uintptr_t>(start_);
1278 }
1279
1280 // True if the object is a heap object in the address range of this
1281 // semispace (not necessarily below the allocation pointer).
1282 bool Contains(Object* o) {
1283 return (reinterpret_cast<uintptr_t>(o) & object_mask_) == object_expected_;
1284 }
1285
1286 // The offset of an address from the beginning of the space.
Steve Blockd0582a62009-12-15 09:54:21 +00001287 int SpaceOffsetForAddress(Address addr) {
1288 return static_cast<int>(addr - low());
1289 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001290
Leon Clarkee46be812010-01-19 14:06:41 +00001291 // If we don't have these here then SemiSpace will be abstract. However
1292 // they should never be called.
Steve Blocka7e24c12009-10-30 11:49:00 +00001293 virtual int Size() {
1294 UNREACHABLE();
1295 return 0;
1296 }
1297
Leon Clarkee46be812010-01-19 14:06:41 +00001298 virtual bool ReserveSpace(int bytes) {
1299 UNREACHABLE();
1300 return false;
1301 }
1302
Steve Blocka7e24c12009-10-30 11:49:00 +00001303 bool is_committed() { return committed_; }
1304 bool Commit();
1305 bool Uncommit();
1306
Steve Block6ded16b2010-05-10 14:33:55 +01001307#ifdef ENABLE_HEAP_PROTECTION
1308 // Protect/unprotect the space by marking it read-only/writable.
1309 virtual void Protect() {}
1310 virtual void Unprotect() {}
1311#endif
1312
Steve Blocka7e24c12009-10-30 11:49:00 +00001313#ifdef DEBUG
1314 virtual void Print();
1315 virtual void Verify();
1316#endif
1317
1318 // Returns the current capacity of the semi space.
1319 int Capacity() { return capacity_; }
1320
1321 // Returns the maximum capacity of the semi space.
1322 int MaximumCapacity() { return maximum_capacity_; }
1323
1324 // Returns the initial capacity of the semi space.
1325 int InitialCapacity() { return initial_capacity_; }
1326
1327 private:
1328 // The current and maximum capacity of the space.
1329 int capacity_;
1330 int maximum_capacity_;
1331 int initial_capacity_;
1332
1333 // The start address of the space.
1334 Address start_;
1335 // Used to govern object promotion during mark-compact collection.
1336 Address age_mark_;
1337
1338 // Masks and comparison values to test for containment in this semispace.
1339 uintptr_t address_mask_;
1340 uintptr_t object_mask_;
1341 uintptr_t object_expected_;
1342
1343 bool committed_;
1344
1345 public:
1346 TRACK_MEMORY("SemiSpace")
1347};
1348
1349
1350// A SemiSpaceIterator is an ObjectIterator that iterates over the active
1351// semispace of the heap's new space. It iterates over the objects in the
1352// semispace from a given start address (defaulting to the bottom of the
1353// semispace) to the top of the semispace. New objects allocated after the
1354// iterator is created are not iterated.
1355class SemiSpaceIterator : public ObjectIterator {
1356 public:
1357 // Create an iterator over the objects in the given space. If no start
1358 // address is given, the iterator starts from the bottom of the space. If
1359 // no size function is given, the iterator calls Object::Size().
1360 explicit SemiSpaceIterator(NewSpace* space);
1361 SemiSpaceIterator(NewSpace* space, HeapObjectCallback size_func);
1362 SemiSpaceIterator(NewSpace* space, Address start);
1363
Steve Blocka7e24c12009-10-30 11:49:00 +00001364 HeapObject* next() {
Leon Clarked91b9f72010-01-27 17:25:45 +00001365 if (current_ == limit_) return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00001366
1367 HeapObject* object = HeapObject::FromAddress(current_);
1368 int size = (size_func_ == NULL) ? object->Size() : size_func_(object);
1369
1370 current_ += size;
1371 return object;
1372 }
1373
1374 // Implementation of the ObjectIterator functions.
Steve Blocka7e24c12009-10-30 11:49:00 +00001375 virtual HeapObject* next_object() { return next(); }
1376
1377 private:
1378 void Initialize(NewSpace* space, Address start, Address end,
1379 HeapObjectCallback size_func);
1380
1381 // The semispace.
1382 SemiSpace* space_;
1383 // The current iteration point.
1384 Address current_;
1385 // The end of iteration.
1386 Address limit_;
1387 // The callback function.
1388 HeapObjectCallback size_func_;
1389};
1390
1391
1392// -----------------------------------------------------------------------------
1393// The young generation space.
1394//
1395// The new space consists of a contiguous pair of semispaces. It simply
1396// forwards most functions to the appropriate semispace.
1397
1398class NewSpace : public Space {
1399 public:
1400 // Constructor.
1401 NewSpace() : Space(NEW_SPACE, NOT_EXECUTABLE) {}
1402
1403 // Sets up the new space using the given chunk.
1404 bool Setup(Address start, int size);
1405
1406 // Tears down the space. Heap memory was not allocated by the space, so it
1407 // is not deallocated here.
1408 void TearDown();
1409
1410 // True if the space has been set up but not torn down.
1411 bool HasBeenSetup() {
1412 return to_space_.HasBeenSetup() && from_space_.HasBeenSetup();
1413 }
1414
1415 // Flip the pair of spaces.
1416 void Flip();
1417
1418 // Grow the capacity of the semispaces. Assumes that they are not at
1419 // their maximum capacity.
1420 void Grow();
1421
1422 // Shrink the capacity of the semispaces.
1423 void Shrink();
1424
1425 // True if the address or object lies in the address range of either
1426 // semispace (not necessarily below the allocation pointer).
1427 bool Contains(Address a) {
1428 return (reinterpret_cast<uintptr_t>(a) & address_mask_)
1429 == reinterpret_cast<uintptr_t>(start_);
1430 }
1431 bool Contains(Object* o) {
1432 return (reinterpret_cast<uintptr_t>(o) & object_mask_) == object_expected_;
1433 }
1434
1435 // Return the allocated bytes in the active semispace.
Steve Blockd0582a62009-12-15 09:54:21 +00001436 virtual int Size() { return static_cast<int>(top() - bottom()); }
Steve Block3ce2e202009-11-05 08:53:23 +00001437
Steve Blocka7e24c12009-10-30 11:49:00 +00001438 // Return the current capacity of a semispace.
1439 int Capacity() {
1440 ASSERT(to_space_.Capacity() == from_space_.Capacity());
1441 return to_space_.Capacity();
1442 }
Steve Block3ce2e202009-11-05 08:53:23 +00001443
1444 // Return the total amount of memory committed for new space.
1445 int CommittedMemory() {
1446 if (from_space_.is_committed()) return 2 * Capacity();
1447 return Capacity();
1448 }
1449
Steve Blocka7e24c12009-10-30 11:49:00 +00001450 // Return the available bytes without growing in the active semispace.
1451 int Available() { return Capacity() - Size(); }
1452
1453 // Return the maximum capacity of a semispace.
1454 int MaximumCapacity() {
1455 ASSERT(to_space_.MaximumCapacity() == from_space_.MaximumCapacity());
1456 return to_space_.MaximumCapacity();
1457 }
1458
1459 // Returns the initial capacity of a semispace.
1460 int InitialCapacity() {
1461 ASSERT(to_space_.InitialCapacity() == from_space_.InitialCapacity());
1462 return to_space_.InitialCapacity();
1463 }
1464
1465 // Return the address of the allocation pointer in the active semispace.
1466 Address top() { return allocation_info_.top; }
1467 // Return the address of the first object in the active semispace.
1468 Address bottom() { return to_space_.low(); }
1469
1470 // Get the age mark of the inactive semispace.
1471 Address age_mark() { return from_space_.age_mark(); }
1472 // Set the age mark in the active semispace.
1473 void set_age_mark(Address mark) { to_space_.set_age_mark(mark); }
1474
1475 // The start address of the space and a bit mask. Anding an address in the
1476 // new space with the mask will result in the start address.
1477 Address start() { return start_; }
1478 uintptr_t mask() { return address_mask_; }
1479
1480 // The allocation top and limit addresses.
1481 Address* allocation_top_address() { return &allocation_info_.top; }
1482 Address* allocation_limit_address() { return &allocation_info_.limit; }
1483
1484 Object* AllocateRaw(int size_in_bytes) {
1485 return AllocateRawInternal(size_in_bytes, &allocation_info_);
1486 }
1487
1488 // Allocate the requested number of bytes for relocation during mark-compact
1489 // collection.
1490 Object* MCAllocateRaw(int size_in_bytes) {
1491 return AllocateRawInternal(size_in_bytes, &mc_forwarding_info_);
1492 }
1493
1494 // Reset the allocation pointer to the beginning of the active semispace.
1495 void ResetAllocationInfo();
1496 // Reset the reloction pointer to the bottom of the inactive semispace in
1497 // preparation for mark-compact collection.
1498 void MCResetRelocationInfo();
1499 // Update the allocation pointer in the active semispace after a
1500 // mark-compact collection.
1501 void MCCommitRelocationInfo();
1502
1503 // Get the extent of the inactive semispace (for use as a marking stack).
1504 Address FromSpaceLow() { return from_space_.low(); }
1505 Address FromSpaceHigh() { return from_space_.high(); }
1506
1507 // Get the extent of the active semispace (to sweep newly copied objects
1508 // during a scavenge collection).
1509 Address ToSpaceLow() { return to_space_.low(); }
1510 Address ToSpaceHigh() { return to_space_.high(); }
1511
1512 // Offsets from the beginning of the semispaces.
1513 int ToSpaceOffsetForAddress(Address a) {
1514 return to_space_.SpaceOffsetForAddress(a);
1515 }
1516 int FromSpaceOffsetForAddress(Address a) {
1517 return from_space_.SpaceOffsetForAddress(a);
1518 }
1519
1520 // True if the object is a heap object in the address range of the
1521 // respective semispace (not necessarily below the allocation pointer of the
1522 // semispace).
1523 bool ToSpaceContains(Object* o) { return to_space_.Contains(o); }
1524 bool FromSpaceContains(Object* o) { return from_space_.Contains(o); }
1525
1526 bool ToSpaceContains(Address a) { return to_space_.Contains(a); }
1527 bool FromSpaceContains(Address a) { return from_space_.Contains(a); }
1528
Leon Clarkee46be812010-01-19 14:06:41 +00001529 virtual bool ReserveSpace(int bytes);
1530
Steve Blocka7e24c12009-10-30 11:49:00 +00001531#ifdef ENABLE_HEAP_PROTECTION
1532 // Protect/unprotect the space by marking it read-only/writable.
1533 virtual void Protect();
1534 virtual void Unprotect();
1535#endif
1536
1537#ifdef DEBUG
1538 // Verify the active semispace.
1539 virtual void Verify();
1540 // Print the active semispace.
1541 virtual void Print() { to_space_.Print(); }
1542#endif
1543
1544#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1545 // Iterates the active semispace to collect statistics.
1546 void CollectStatistics();
1547 // Reports previously collected statistics of the active semispace.
1548 void ReportStatistics();
1549 // Clears previously collected statistics.
1550 void ClearHistograms();
1551
1552 // Record the allocation or promotion of a heap object. Note that we don't
1553 // record every single allocation, but only those that happen in the
1554 // to space during a scavenge GC.
1555 void RecordAllocation(HeapObject* obj);
1556 void RecordPromotion(HeapObject* obj);
1557#endif
1558
1559 // Return whether the operation succeded.
1560 bool CommitFromSpaceIfNeeded() {
1561 if (from_space_.is_committed()) return true;
1562 return from_space_.Commit();
1563 }
1564
1565 bool UncommitFromSpace() {
1566 if (!from_space_.is_committed()) return true;
1567 return from_space_.Uncommit();
1568 }
1569
1570 private:
1571 // The semispaces.
1572 SemiSpace to_space_;
1573 SemiSpace from_space_;
1574
1575 // Start address and bit mask for containment testing.
1576 Address start_;
1577 uintptr_t address_mask_;
1578 uintptr_t object_mask_;
1579 uintptr_t object_expected_;
1580
1581 // Allocation pointer and limit for normal allocation and allocation during
1582 // mark-compact collection.
1583 AllocationInfo allocation_info_;
1584 AllocationInfo mc_forwarding_info_;
1585
1586#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1587 HistogramInfo* allocated_histogram_;
1588 HistogramInfo* promoted_histogram_;
1589#endif
1590
1591 // Implementation of AllocateRaw and MCAllocateRaw.
1592 inline Object* AllocateRawInternal(int size_in_bytes,
1593 AllocationInfo* alloc_info);
1594
1595 friend class SemiSpaceIterator;
1596
1597 public:
1598 TRACK_MEMORY("NewSpace")
1599};
1600
1601
1602// -----------------------------------------------------------------------------
1603// Free lists for old object spaces
1604//
1605// Free-list nodes are free blocks in the heap. They look like heap objects
1606// (free-list node pointers have the heap object tag, and they have a map like
1607// a heap object). They have a size and a next pointer. The next pointer is
1608// the raw address of the next free list node (or NULL).
1609class FreeListNode: public HeapObject {
1610 public:
1611 // Obtain a free-list node from a raw address. This is not a cast because
1612 // it does not check nor require that the first word at the address is a map
1613 // pointer.
1614 static FreeListNode* FromAddress(Address address) {
1615 return reinterpret_cast<FreeListNode*>(HeapObject::FromAddress(address));
1616 }
1617
Steve Block3ce2e202009-11-05 08:53:23 +00001618 static inline bool IsFreeListNode(HeapObject* object);
1619
Steve Blocka7e24c12009-10-30 11:49:00 +00001620 // Set the size in bytes, which can be read with HeapObject::Size(). This
1621 // function also writes a map to the first word of the block so that it
1622 // looks like a heap object to the garbage collector and heap iteration
1623 // functions.
1624 void set_size(int size_in_bytes);
1625
1626 // Accessors for the next field.
1627 inline Address next();
1628 inline void set_next(Address next);
1629
1630 private:
1631 static const int kNextOffset = POINTER_SIZE_ALIGN(ByteArray::kHeaderSize);
1632
1633 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeListNode);
1634};
1635
1636
1637// The free list for the old space.
1638class OldSpaceFreeList BASE_EMBEDDED {
1639 public:
1640 explicit OldSpaceFreeList(AllocationSpace owner);
1641
1642 // Clear the free list.
1643 void Reset();
1644
1645 // Return the number of bytes available on the free list.
1646 int available() { return available_; }
1647
1648 // Place a node on the free list. The block of size 'size_in_bytes'
1649 // starting at 'start' is placed on the free list. The return value is the
1650 // number of bytes that have been lost due to internal fragmentation by
1651 // freeing the block. Bookkeeping information will be written to the block,
1652 // ie, its contents will be destroyed. The start address should be word
1653 // aligned, and the size should be a non-zero multiple of the word size.
1654 int Free(Address start, int size_in_bytes);
1655
1656 // Allocate a block of size 'size_in_bytes' from the free list. The block
1657 // is unitialized. A failure is returned if no block is available. The
1658 // number of bytes lost to fragmentation is returned in the output parameter
1659 // 'wasted_bytes'. The size should be a non-zero multiple of the word size.
1660 Object* Allocate(int size_in_bytes, int* wasted_bytes);
1661
1662 private:
1663 // The size range of blocks, in bytes. (Smaller allocations are allowed, but
1664 // will always result in waste.)
1665 static const int kMinBlockSize = 2 * kPointerSize;
1666 static const int kMaxBlockSize = Page::kMaxHeapObjectSize;
1667
1668 // The identity of the owning space, for building allocation Failure
1669 // objects.
1670 AllocationSpace owner_;
1671
1672 // Total available bytes in all blocks on this free list.
1673 int available_;
1674
1675 // Blocks are put on exact free lists in an array, indexed by size in words.
1676 // The available sizes are kept in an increasingly ordered list. Entries
1677 // corresponding to sizes < kMinBlockSize always have an empty free list
1678 // (but index kHead is used for the head of the size list).
1679 struct SizeNode {
1680 // Address of the head FreeListNode of the implied block size or NULL.
1681 Address head_node_;
1682 // Size (words) of the next larger available size if head_node_ != NULL.
1683 int next_size_;
1684 };
1685 static const int kFreeListsLength = kMaxBlockSize / kPointerSize + 1;
1686 SizeNode free_[kFreeListsLength];
1687
1688 // Sentinel elements for the size list. Real elements are in ]kHead..kEnd[.
1689 static const int kHead = kMinBlockSize / kPointerSize - 1;
1690 static const int kEnd = kMaxInt;
1691
1692 // We keep a "finger" in the size list to speed up a common pattern:
1693 // repeated requests for the same or increasing sizes.
1694 int finger_;
1695
1696 // Starting from *prev, find and return the smallest size >= index (words),
1697 // or kEnd. Update *prev to be the largest size < index, or kHead.
1698 int FindSize(int index, int* prev) {
1699 int cur = free_[*prev].next_size_;
1700 while (cur < index) {
1701 *prev = cur;
1702 cur = free_[cur].next_size_;
1703 }
1704 return cur;
1705 }
1706
1707 // Remove an existing element from the size list.
1708 void RemoveSize(int index) {
1709 int prev = kHead;
1710 int cur = FindSize(index, &prev);
1711 ASSERT(cur == index);
1712 free_[prev].next_size_ = free_[cur].next_size_;
1713 finger_ = prev;
1714 }
1715
1716 // Insert a new element into the size list.
1717 void InsertSize(int index) {
1718 int prev = kHead;
1719 int cur = FindSize(index, &prev);
1720 ASSERT(cur != index);
1721 free_[prev].next_size_ = index;
1722 free_[index].next_size_ = cur;
1723 }
1724
1725 // The size list is not updated during a sequence of calls to Free, but is
1726 // rebuilt before the next allocation.
1727 void RebuildSizeList();
1728 bool needs_rebuild_;
1729
1730#ifdef DEBUG
1731 // Does this free list contain a free block located at the address of 'node'?
1732 bool Contains(FreeListNode* node);
1733#endif
1734
1735 DISALLOW_COPY_AND_ASSIGN(OldSpaceFreeList);
1736};
1737
1738
1739// The free list for the map space.
1740class FixedSizeFreeList BASE_EMBEDDED {
1741 public:
1742 FixedSizeFreeList(AllocationSpace owner, int object_size);
1743
1744 // Clear the free list.
1745 void Reset();
1746
1747 // Return the number of bytes available on the free list.
1748 int available() { return available_; }
1749
1750 // Place a node on the free list. The block starting at 'start' (assumed to
1751 // have size object_size_) is placed on the free list. Bookkeeping
1752 // information will be written to the block, ie, its contents will be
1753 // destroyed. The start address should be word aligned.
1754 void Free(Address start);
1755
1756 // Allocate a fixed sized block from the free list. The block is unitialized.
1757 // A failure is returned if no block is available.
1758 Object* Allocate();
1759
1760 private:
1761 // Available bytes on the free list.
1762 int available_;
1763
1764 // The head of the free list.
1765 Address head_;
1766
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001767 // The tail of the free list.
1768 Address tail_;
1769
Steve Blocka7e24c12009-10-30 11:49:00 +00001770 // The identity of the owning space, for building allocation Failure
1771 // objects.
1772 AllocationSpace owner_;
1773
1774 // The size of the objects in this space.
1775 int object_size_;
1776
1777 DISALLOW_COPY_AND_ASSIGN(FixedSizeFreeList);
1778};
1779
1780
1781// -----------------------------------------------------------------------------
1782// Old object space (excluding map objects)
1783
1784class OldSpace : public PagedSpace {
1785 public:
1786 // Creates an old space object with a given maximum capacity.
1787 // The constructor does not allocate pages from OS.
1788 explicit OldSpace(int max_capacity,
1789 AllocationSpace id,
1790 Executability executable)
1791 : PagedSpace(max_capacity, id, executable), free_list_(id) {
1792 page_extra_ = 0;
1793 }
1794
1795 // The bytes available on the free list (ie, not above the linear allocation
1796 // pointer).
1797 int AvailableFree() { return free_list_.available(); }
1798
Steve Block6ded16b2010-05-10 14:33:55 +01001799 // The limit of allocation for a page in this space.
1800 virtual Address PageAllocationLimit(Page* page) {
1801 return page->ObjectAreaEnd();
Steve Blocka7e24c12009-10-30 11:49:00 +00001802 }
1803
1804 // Give a block of memory to the space's free list. It might be added to
1805 // the free list or accounted as waste.
Steve Block6ded16b2010-05-10 14:33:55 +01001806 // If add_to_freelist is false then just accounting stats are updated and
1807 // no attempt to add area to free list is made.
1808 void Free(Address start, int size_in_bytes, bool add_to_freelist) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001809 accounting_stats_.DeallocateBytes(size_in_bytes);
Steve Block6ded16b2010-05-10 14:33:55 +01001810
1811 if (add_to_freelist) {
1812 int wasted_bytes = free_list_.Free(start, size_in_bytes);
1813 accounting_stats_.WasteBytes(wasted_bytes);
1814 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001815 }
1816
1817 // Prepare for full garbage collection. Resets the relocation pointer and
1818 // clears the free list.
1819 virtual void PrepareForMarkCompact(bool will_compact);
1820
1821 // Updates the allocation pointer to the relocation top after a mark-compact
1822 // collection.
1823 virtual void MCCommitRelocationInfo();
1824
Leon Clarkee46be812010-01-19 14:06:41 +00001825 virtual void PutRestOfCurrentPageOnFreeList(Page* current_page);
1826
Steve Blocka7e24c12009-10-30 11:49:00 +00001827#ifdef DEBUG
1828 // Reports statistics for the space
1829 void ReportStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00001830#endif
1831
1832 protected:
1833 // Virtual function in the superclass. Slow path of AllocateRaw.
1834 HeapObject* SlowAllocateRaw(int size_in_bytes);
1835
1836 // Virtual function in the superclass. Allocate linearly at the start of
1837 // the page after current_page (there is assumed to be one).
1838 HeapObject* AllocateInNextPage(Page* current_page, int size_in_bytes);
1839
1840 private:
1841 // The space's free list.
1842 OldSpaceFreeList free_list_;
1843
1844 public:
1845 TRACK_MEMORY("OldSpace")
1846};
1847
1848
1849// -----------------------------------------------------------------------------
1850// Old space for objects of a fixed size
1851
1852class FixedSpace : public PagedSpace {
1853 public:
1854 FixedSpace(int max_capacity,
1855 AllocationSpace id,
1856 int object_size_in_bytes,
1857 const char* name)
1858 : PagedSpace(max_capacity, id, NOT_EXECUTABLE),
1859 object_size_in_bytes_(object_size_in_bytes),
1860 name_(name),
1861 free_list_(id, object_size_in_bytes) {
1862 page_extra_ = Page::kObjectAreaSize % object_size_in_bytes;
1863 }
1864
Steve Block6ded16b2010-05-10 14:33:55 +01001865 // The limit of allocation for a page in this space.
1866 virtual Address PageAllocationLimit(Page* page) {
1867 return page->ObjectAreaEnd() - page_extra_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001868 }
1869
1870 int object_size_in_bytes() { return object_size_in_bytes_; }
1871
1872 // Give a fixed sized block of memory to the space's free list.
Steve Block6ded16b2010-05-10 14:33:55 +01001873 // If add_to_freelist is false then just accounting stats are updated and
1874 // no attempt to add area to free list is made.
1875 void Free(Address start, bool add_to_freelist) {
1876 if (add_to_freelist) {
1877 free_list_.Free(start);
1878 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001879 accounting_stats_.DeallocateBytes(object_size_in_bytes_);
1880 }
1881
1882 // Prepares for a mark-compact GC.
1883 virtual void PrepareForMarkCompact(bool will_compact);
1884
1885 // Updates the allocation pointer to the relocation top after a mark-compact
1886 // collection.
1887 virtual void MCCommitRelocationInfo();
1888
Leon Clarkee46be812010-01-19 14:06:41 +00001889 virtual void PutRestOfCurrentPageOnFreeList(Page* current_page);
1890
Steve Blocka7e24c12009-10-30 11:49:00 +00001891#ifdef DEBUG
1892 // Reports statistic info of the space
1893 void ReportStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00001894#endif
1895
1896 protected:
1897 // Virtual function in the superclass. Slow path of AllocateRaw.
1898 HeapObject* SlowAllocateRaw(int size_in_bytes);
1899
1900 // Virtual function in the superclass. Allocate linearly at the start of
1901 // the page after current_page (there is assumed to be one).
1902 HeapObject* AllocateInNextPage(Page* current_page, int size_in_bytes);
1903
Leon Clarkee46be812010-01-19 14:06:41 +00001904 void ResetFreeList() {
1905 free_list_.Reset();
1906 }
1907
Steve Blocka7e24c12009-10-30 11:49:00 +00001908 private:
1909 // The size of objects in this space.
1910 int object_size_in_bytes_;
1911
1912 // The name of this space.
1913 const char* name_;
1914
1915 // The space's free list.
1916 FixedSizeFreeList free_list_;
1917};
1918
1919
1920// -----------------------------------------------------------------------------
1921// Old space for all map objects
1922
1923class MapSpace : public FixedSpace {
1924 public:
1925 // Creates a map space object with a maximum capacity.
Leon Clarked91b9f72010-01-27 17:25:45 +00001926 MapSpace(int max_capacity, int max_map_space_pages, AllocationSpace id)
1927 : FixedSpace(max_capacity, id, Map::kSize, "map"),
1928 max_map_space_pages_(max_map_space_pages) {
1929 ASSERT(max_map_space_pages < kMaxMapPageIndex);
1930 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001931
1932 // Prepares for a mark-compact GC.
1933 virtual void PrepareForMarkCompact(bool will_compact);
1934
1935 // Given an index, returns the page address.
1936 Address PageAddress(int page_index) { return page_addresses_[page_index]; }
1937
Leon Clarked91b9f72010-01-27 17:25:45 +00001938 static const int kMaxMapPageIndex = 1 << MapWord::kMapPageIndexBits;
Steve Blocka7e24c12009-10-30 11:49:00 +00001939
Leon Clarkee46be812010-01-19 14:06:41 +00001940 // Are map pointers encodable into map word?
1941 bool MapPointersEncodable() {
1942 if (!FLAG_use_big_map_space) {
Leon Clarked91b9f72010-01-27 17:25:45 +00001943 ASSERT(CountPagesToTop() <= kMaxMapPageIndex);
Leon Clarkee46be812010-01-19 14:06:41 +00001944 return true;
1945 }
Leon Clarked91b9f72010-01-27 17:25:45 +00001946 return CountPagesToTop() <= max_map_space_pages_;
Leon Clarkee46be812010-01-19 14:06:41 +00001947 }
1948
1949 // Should be called after forced sweep to find out if map space needs
1950 // compaction.
1951 bool NeedsCompaction(int live_maps) {
Leon Clarked91b9f72010-01-27 17:25:45 +00001952 return !MapPointersEncodable() && live_maps <= CompactionThreshold();
Leon Clarkee46be812010-01-19 14:06:41 +00001953 }
1954
1955 Address TopAfterCompaction(int live_maps) {
1956 ASSERT(NeedsCompaction(live_maps));
1957
1958 int pages_left = live_maps / kMapsPerPage;
1959 PageIterator it(this, PageIterator::ALL_PAGES);
1960 while (pages_left-- > 0) {
1961 ASSERT(it.has_next());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001962 it.next()->SetRegionMarks(Page::kAllRegionsCleanMarks);
Leon Clarkee46be812010-01-19 14:06:41 +00001963 }
1964 ASSERT(it.has_next());
1965 Page* top_page = it.next();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001966 top_page->SetRegionMarks(Page::kAllRegionsCleanMarks);
Leon Clarkee46be812010-01-19 14:06:41 +00001967 ASSERT(top_page->is_valid());
1968
1969 int offset = live_maps % kMapsPerPage * Map::kSize;
1970 Address top = top_page->ObjectAreaStart() + offset;
1971 ASSERT(top < top_page->ObjectAreaEnd());
1972 ASSERT(Contains(top));
1973
1974 return top;
1975 }
1976
1977 void FinishCompaction(Address new_top, int live_maps) {
1978 Page* top_page = Page::FromAddress(new_top);
1979 ASSERT(top_page->is_valid());
1980
1981 SetAllocationInfo(&allocation_info_, top_page);
1982 allocation_info_.top = new_top;
1983
1984 int new_size = live_maps * Map::kSize;
1985 accounting_stats_.DeallocateBytes(accounting_stats_.Size());
1986 accounting_stats_.AllocateBytes(new_size);
1987
1988#ifdef DEBUG
1989 if (FLAG_enable_slow_asserts) {
Leon Clarked91b9f72010-01-27 17:25:45 +00001990 intptr_t actual_size = 0;
Leon Clarkee46be812010-01-19 14:06:41 +00001991 for (Page* p = first_page_; p != top_page; p = p->next_page())
1992 actual_size += kMapsPerPage * Map::kSize;
1993 actual_size += (new_top - top_page->ObjectAreaStart());
1994 ASSERT(accounting_stats_.Size() == actual_size);
1995 }
1996#endif
1997
1998 Shrink();
1999 ResetFreeList();
2000 }
2001
Steve Blocka7e24c12009-10-30 11:49:00 +00002002 protected:
2003#ifdef DEBUG
2004 virtual void VerifyObject(HeapObject* obj);
2005#endif
2006
2007 private:
Leon Clarkee46be812010-01-19 14:06:41 +00002008 static const int kMapsPerPage = Page::kObjectAreaSize / Map::kSize;
2009
2010 // Do map space compaction if there is a page gap.
Leon Clarked91b9f72010-01-27 17:25:45 +00002011 int CompactionThreshold() {
2012 return kMapsPerPage * (max_map_space_pages_ - 1);
2013 }
2014
2015 const int max_map_space_pages_;
Leon Clarkee46be812010-01-19 14:06:41 +00002016
Steve Blocka7e24c12009-10-30 11:49:00 +00002017 // An array of page start address in a map space.
Leon Clarked91b9f72010-01-27 17:25:45 +00002018 Address page_addresses_[kMaxMapPageIndex];
Steve Blocka7e24c12009-10-30 11:49:00 +00002019
2020 public:
2021 TRACK_MEMORY("MapSpace")
2022};
2023
2024
2025// -----------------------------------------------------------------------------
2026// Old space for all global object property cell objects
2027
2028class CellSpace : public FixedSpace {
2029 public:
2030 // Creates a property cell space object with a maximum capacity.
2031 CellSpace(int max_capacity, AllocationSpace id)
2032 : FixedSpace(max_capacity, id, JSGlobalPropertyCell::kSize, "cell") {}
2033
2034 protected:
2035#ifdef DEBUG
2036 virtual void VerifyObject(HeapObject* obj);
2037#endif
2038
2039 public:
2040 TRACK_MEMORY("CellSpace")
2041};
2042
2043
2044// -----------------------------------------------------------------------------
2045// Large objects ( > Page::kMaxHeapObjectSize ) are allocated and managed by
2046// the large object space. A large object is allocated from OS heap with
2047// extra padding bytes (Page::kPageSize + Page::kObjectStartOffset).
2048// A large object always starts at Page::kObjectStartOffset to a page.
2049// Large objects do not move during garbage collections.
2050
2051// A LargeObjectChunk holds exactly one large object page with exactly one
2052// large object.
2053class LargeObjectChunk {
2054 public:
2055 // Allocates a new LargeObjectChunk that contains a large object page
2056 // (Page::kPageSize aligned) that has at least size_in_bytes (for a large
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002057 // object) bytes after the object area start of that page.
2058 // The allocated chunk size is set in the output parameter chunk_size.
Steve Blocka7e24c12009-10-30 11:49:00 +00002059 static LargeObjectChunk* New(int size_in_bytes,
2060 size_t* chunk_size,
2061 Executability executable);
2062
2063 // Interpret a raw address as a large object chunk.
2064 static LargeObjectChunk* FromAddress(Address address) {
2065 return reinterpret_cast<LargeObjectChunk*>(address);
2066 }
2067
2068 // Returns the address of this chunk.
2069 Address address() { return reinterpret_cast<Address>(this); }
2070
2071 // Accessors for the fields of the chunk.
2072 LargeObjectChunk* next() { return next_; }
2073 void set_next(LargeObjectChunk* chunk) { next_ = chunk; }
2074
Steve Block791712a2010-08-27 10:21:07 +01002075 size_t size() { return size_ & ~Page::kPageFlagMask; }
Steve Blocka7e24c12009-10-30 11:49:00 +00002076 void set_size(size_t size_in_bytes) { size_ = size_in_bytes; }
2077
2078 // Returns the object in this chunk.
2079 inline HeapObject* GetObject();
2080
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002081 // Given a requested size returns the physical size of a chunk to be
2082 // allocated.
Steve Blocka7e24c12009-10-30 11:49:00 +00002083 static int ChunkSizeFor(int size_in_bytes);
2084
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002085 // Given a chunk size, returns the object size it can accommodate. Used by
2086 // LargeObjectSpace::Available.
Steve Blocka7e24c12009-10-30 11:49:00 +00002087 static int ObjectSizeFor(int chunk_size) {
2088 if (chunk_size <= (Page::kPageSize + Page::kObjectStartOffset)) return 0;
2089 return chunk_size - Page::kPageSize - Page::kObjectStartOffset;
2090 }
2091
2092 private:
2093 // A pointer to the next large object chunk in the space or NULL.
2094 LargeObjectChunk* next_;
2095
2096 // The size of this chunk.
2097 size_t size_;
2098
2099 public:
2100 TRACK_MEMORY("LargeObjectChunk")
2101};
2102
2103
2104class LargeObjectSpace : public Space {
2105 public:
2106 explicit LargeObjectSpace(AllocationSpace id);
2107 virtual ~LargeObjectSpace() {}
2108
2109 // Initializes internal data structures.
2110 bool Setup();
2111
2112 // Releases internal resources, frees objects in this space.
2113 void TearDown();
2114
2115 // Allocates a (non-FixedArray, non-Code) large object.
2116 Object* AllocateRaw(int size_in_bytes);
2117 // Allocates a large Code object.
2118 Object* AllocateRawCode(int size_in_bytes);
2119 // Allocates a large FixedArray.
2120 Object* AllocateRawFixedArray(int size_in_bytes);
2121
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002122 // Available bytes for objects in this space.
Steve Blocka7e24c12009-10-30 11:49:00 +00002123 int Available() {
2124 return LargeObjectChunk::ObjectSizeFor(MemoryAllocator::Available());
2125 }
2126
2127 virtual int Size() {
2128 return size_;
2129 }
2130
2131 int PageCount() {
2132 return page_count_;
2133 }
2134
2135 // Finds an object for a given address, returns Failure::Exception()
2136 // if it is not found. The function iterates through all objects in this
2137 // space, may be slow.
2138 Object* FindObject(Address a);
2139
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002140 // Iterates objects covered by dirty regions.
2141 void IterateDirtyRegions(ObjectSlotCallback func);
Steve Blocka7e24c12009-10-30 11:49:00 +00002142
2143 // Frees unmarked objects.
2144 void FreeUnmarkedObjects();
2145
2146 // Checks whether a heap object is in this space; O(1).
2147 bool Contains(HeapObject* obj);
2148
2149 // Checks whether the space is empty.
2150 bool IsEmpty() { return first_chunk_ == NULL; }
2151
Leon Clarkee46be812010-01-19 14:06:41 +00002152 // See the comments for ReserveSpace in the Space class. This has to be
2153 // called after ReserveSpace has been called on the paged spaces, since they
2154 // may use some memory, leaving less for large objects.
2155 virtual bool ReserveSpace(int bytes);
2156
Steve Blocka7e24c12009-10-30 11:49:00 +00002157#ifdef ENABLE_HEAP_PROTECTION
2158 // Protect/unprotect the space by marking it read-only/writable.
2159 void Protect();
2160 void Unprotect();
2161#endif
2162
2163#ifdef DEBUG
2164 virtual void Verify();
2165 virtual void Print();
2166 void ReportStatistics();
2167 void CollectCodeStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00002168#endif
2169 // Checks whether an address is in the object area in this space. It
2170 // iterates all objects in the space. May be slow.
2171 bool SlowContains(Address addr) { return !FindObject(addr)->IsFailure(); }
2172
2173 private:
2174 // The head of the linked list of large object chunks.
2175 LargeObjectChunk* first_chunk_;
2176 int size_; // allocated bytes
2177 int page_count_; // number of chunks
2178
2179
2180 // Shared implementation of AllocateRaw, AllocateRawCode and
2181 // AllocateRawFixedArray.
2182 Object* AllocateRawInternal(int requested_size,
2183 int object_size,
2184 Executability executable);
2185
Steve Blocka7e24c12009-10-30 11:49:00 +00002186 friend class LargeObjectIterator;
2187
2188 public:
2189 TRACK_MEMORY("LargeObjectSpace")
2190};
2191
2192
2193class LargeObjectIterator: public ObjectIterator {
2194 public:
2195 explicit LargeObjectIterator(LargeObjectSpace* space);
2196 LargeObjectIterator(LargeObjectSpace* space, HeapObjectCallback size_func);
2197
Steve Blocka7e24c12009-10-30 11:49:00 +00002198 HeapObject* next();
2199
2200 // implementation of ObjectIterator.
Steve Blocka7e24c12009-10-30 11:49:00 +00002201 virtual HeapObject* next_object() { return next(); }
2202
2203 private:
2204 LargeObjectChunk* current_;
2205 HeapObjectCallback size_func_;
2206};
2207
2208
2209} } // namespace v8::internal
2210
2211#endif // V8_SPACES_H_