1 //! The arena, a fast but limited type of allocator.
3 //! Arenas are a type of allocator that destroy the objects within, all at
4 //! once, once the arena itself is destroyed. They do not support deallocation
5 //! of individual objects while the arena itself is still alive. The benefit
6 //! of an arena is very fast allocation; just a pointer bump.
8 //! This crate implements several kinds of arena.
11 html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
12 test(no_crate_inject, attr(deny(warnings)))
14 #![feature(dropck_eyepatch)]
15 #![feature(new_uninit)]
16 #![feature(maybe_uninit_slice)]
17 #![feature(min_specialization)]
18 #![feature(decl_macro)]
19 #![feature(rustc_attrs)]
20 #![cfg_attr(test, feature(test))]
22 use smallvec::SmallVec;
24 use std::alloc::Layout;
25 use std::cell::{Cell, RefCell};
27 use std::marker::{PhantomData, Send};
28 use std::mem::{self, MaybeUninit};
34 fn cold_path<F: FnOnce() -> R, R>(f: F) -> R {
38 /// An arena that can hold objects of only one type.
39 pub struct TypedArena<T> {
40 /// A pointer to the next object to be allocated.
43 /// A pointer to the end of the allocated area. When this pointer is
44 /// reached, a new chunk is allocated.
47 /// A vector of arena chunks.
48 chunks: RefCell<Vec<ArenaChunk<T>>>,
50 /// Marker indicating that dropping the arena causes its owned
51 /// instances of `T` to be dropped.
55 struct ArenaChunk<T = u8> {
56 /// The raw storage for the arena chunk.
57 storage: Box<[MaybeUninit<T>]>,
58 /// The number of valid entries in the chunk.
62 impl<T> ArenaChunk<T> {
64 unsafe fn new(capacity: usize) -> ArenaChunk<T> {
65 ArenaChunk { storage: Box::new_uninit_slice(capacity), entries: 0 }
68 /// Destroys this arena chunk.
70 unsafe fn destroy(&mut self, len: usize) {
71 // The branch on needs_drop() is an -O1 performance optimization.
72 // Without the branch, dropping TypedArena<u8> takes linear time.
73 if mem::needs_drop::<T>() {
74 ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(&mut self.storage[..len]));
78 // Returns a pointer to the first allocated object.
80 fn start(&mut self) -> *mut T {
81 MaybeUninit::slice_as_mut_ptr(&mut self.storage)
84 // Returns a pointer to the end of the allocated space.
86 fn end(&mut self) -> *mut T {
88 if mem::size_of::<T>() == 0 {
89 // A pointer as large as possible for zero-sized elements.
92 self.start().add(self.storage.len())
98 // The arenas start with PAGE-sized chunks, and then each new chunk is twice as
99 // big as its predecessor, up until we reach HUGE_PAGE-sized chunks, whereupon
100 // we stop growing. This scales well, from arenas that are barely used up to
101 // arenas that are used for 100s of MiBs. Note also that the chosen sizes match
102 // the usual sizes of pages and huge pages on Linux.
103 const PAGE: usize = 4096;
104 const HUGE_PAGE: usize = 2 * 1024 * 1024;
106 impl<T> Default for TypedArena<T> {
107 /// Creates a new `TypedArena`.
108 fn default() -> TypedArena<T> {
110 // We set both `ptr` and `end` to 0 so that the first call to
111 // alloc() will trigger a grow().
112 ptr: Cell::new(ptr::null_mut()),
113 end: Cell::new(ptr::null_mut()),
114 chunks: Default::default(),
121 fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T];
124 impl<I, T> IterExt<T> for I
126 I: IntoIterator<Item = T>,
128 // This default collects into a `SmallVec` and then allocates by copying
129 // from it. The specializations below for types like `Vec` are more
130 // efficient, copying directly without the intermediate collecting step.
131 // This default could be made more efficient, like
132 // `DroplessArena::alloc_from_iter`, but it's not hot enough to bother.
134 default fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
135 let vec: SmallVec<[_; 8]> = self.into_iter().collect();
136 vec.alloc_from_iter(arena)
140 impl<T, const N: usize> IterExt<T> for std::array::IntoIter<T, N> {
142 fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
143 let len = self.len();
147 // Move the content to the arena by copying and then forgetting it.
149 let start_ptr = arena.alloc_raw_slice(len);
150 self.as_slice().as_ptr().copy_to_nonoverlapping(start_ptr, len);
152 slice::from_raw_parts_mut(start_ptr, len)
157 impl<T> IterExt<T> for Vec<T> {
159 fn alloc_from_iter(mut self, arena: &TypedArena<T>) -> &mut [T] {
160 let len = self.len();
164 // Move the content to the arena by copying and then forgetting it.
166 let start_ptr = arena.alloc_raw_slice(len);
167 self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
169 slice::from_raw_parts_mut(start_ptr, len)
174 impl<A: smallvec::Array> IterExt<A::Item> for SmallVec<A> {
176 fn alloc_from_iter(mut self, arena: &TypedArena<A::Item>) -> &mut [A::Item] {
177 let len = self.len();
181 // Move the content to the arena by copying and then forgetting it.
183 let start_ptr = arena.alloc_raw_slice(len);
184 self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
186 slice::from_raw_parts_mut(start_ptr, len)
191 impl<T> TypedArena<T> {
192 /// Allocates an object in the `TypedArena`, returning a reference to it.
194 pub fn alloc(&self, object: T) -> &mut T {
195 if self.ptr == self.end {
200 if mem::size_of::<T>() == 0 {
201 self.ptr.set((self.ptr.get() as *mut u8).wrapping_offset(1) as *mut T);
202 let ptr = mem::align_of::<T>() as *mut T;
203 // Don't drop the object. This `write` is equivalent to `forget`.
204 ptr::write(ptr, object);
207 let ptr = self.ptr.get();
208 // Advance the pointer.
209 self.ptr.set(self.ptr.get().offset(1));
210 // Write into uninitialized memory.
211 ptr::write(ptr, object);
218 fn can_allocate(&self, additional: usize) -> bool {
219 let available_bytes = self.end.get() as usize - self.ptr.get() as usize;
220 let additional_bytes = additional.checked_mul(mem::size_of::<T>()).unwrap();
221 available_bytes >= additional_bytes
224 /// Ensures there's enough space in the current chunk to fit `len` objects.
226 fn ensure_capacity(&self, additional: usize) {
227 if !self.can_allocate(additional) {
228 self.grow(additional);
229 debug_assert!(self.can_allocate(additional));
234 unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
235 assert!(mem::size_of::<T>() != 0);
238 self.ensure_capacity(len);
240 let start_ptr = self.ptr.get();
241 self.ptr.set(start_ptr.add(len));
246 pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
247 assert!(mem::size_of::<T>() != 0);
248 iter.alloc_from_iter(self)
254 fn grow(&self, additional: usize) {
256 // We need the element size to convert chunk sizes (ranging from
257 // PAGE to HUGE_PAGE bytes) to element counts.
258 let elem_size = cmp::max(1, mem::size_of::<T>());
259 let mut chunks = self.chunks.borrow_mut();
261 if let Some(last_chunk) = chunks.last_mut() {
262 // If a type is `!needs_drop`, we don't need to keep track of how many elements
263 // the chunk stores - the field will be ignored anyway.
264 if mem::needs_drop::<T>() {
265 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
266 last_chunk.entries = used_bytes / mem::size_of::<T>();
269 // If the previous chunk's len is less than HUGE_PAGE
270 // bytes, then this chunk will be least double the previous
272 new_cap = last_chunk.storage.len().min(HUGE_PAGE / elem_size / 2);
275 new_cap = PAGE / elem_size;
277 // Also ensure that this chunk can fit `additional`.
278 new_cap = cmp::max(additional, new_cap);
280 let mut chunk = ArenaChunk::<T>::new(new_cap);
281 self.ptr.set(chunk.start());
282 self.end.set(chunk.end());
287 // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
289 fn clear_last_chunk(&self, last_chunk: &mut ArenaChunk<T>) {
290 // Determine how much was filled.
291 let start = last_chunk.start() as usize;
292 // We obtain the value of the pointer to the first uninitialized element.
293 let end = self.ptr.get() as usize;
294 // We then calculate the number of elements to be dropped in the last chunk,
295 // which is the filled area's length.
296 let diff = if mem::size_of::<T>() == 0 {
297 // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
298 // the number of zero-sized values in the last and only chunk, just out of caution.
299 // Recall that `end` was incremented for each allocated value.
302 (end - start) / mem::size_of::<T>()
304 // Pass that to the `destroy` method.
306 last_chunk.destroy(diff);
309 self.ptr.set(last_chunk.start());
313 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
316 // Determine how much was filled.
317 let mut chunks_borrow = self.chunks.borrow_mut();
318 if let Some(mut last_chunk) = chunks_borrow.pop() {
319 // Drop the contents of the last chunk.
320 self.clear_last_chunk(&mut last_chunk);
321 // The last chunk will be dropped. Destroy all other chunks.
322 for chunk in chunks_borrow.iter_mut() {
323 chunk.destroy(chunk.entries);
326 // Box handles deallocation of `last_chunk` and `self.chunks`.
331 unsafe impl<T: Send> Send for TypedArena<T> {}
333 /// An arena that can hold objects of multiple different types that impl `Copy`
334 /// and/or satisfy `!mem::needs_drop`.
335 pub struct DroplessArena {
336 /// A pointer to the start of the free space.
337 start: Cell<*mut u8>,
339 /// A pointer to the end of free space.
341 /// The allocation proceeds downwards from the end of the chunk towards the
342 /// start. (This is slightly simpler and faster than allocating upwards,
343 /// see <https://fitzgeraldnick.com/2019/11/01/always-bump-downwards.html>.)
344 /// When this pointer crosses the start pointer, a new chunk is allocated.
347 /// A vector of arena chunks.
348 chunks: RefCell<Vec<ArenaChunk>>,
351 unsafe impl Send for DroplessArena {}
353 impl Default for DroplessArena {
355 fn default() -> DroplessArena {
357 start: Cell::new(ptr::null_mut()),
358 end: Cell::new(ptr::null_mut()),
359 chunks: Default::default(),
367 fn grow(&self, additional: usize) {
369 let mut chunks = self.chunks.borrow_mut();
371 if let Some(last_chunk) = chunks.last_mut() {
372 // There is no need to update `last_chunk.entries` because that
373 // field isn't used by `DroplessArena`.
375 // If the previous chunk's len is less than HUGE_PAGE
376 // bytes, then this chunk will be least double the previous
378 new_cap = last_chunk.storage.len().min(HUGE_PAGE / 2);
383 // Also ensure that this chunk can fit `additional`.
384 new_cap = cmp::max(additional, new_cap);
386 let mut chunk = ArenaChunk::new(new_cap);
387 self.start.set(chunk.start());
388 self.end.set(chunk.end());
393 /// Allocates a byte slice with specified layout from the current memory
394 /// chunk. Returns `None` if there is no free space left to satisfy the
397 fn alloc_raw_without_grow(&self, layout: Layout) -> Option<*mut u8> {
398 let start = self.start.get() as usize;
399 let end = self.end.get() as usize;
401 let align = layout.align();
402 let bytes = layout.size();
404 let new_end = end.checked_sub(bytes)? & !(align - 1);
405 if start <= new_end {
406 let new_end = new_end as *mut u8;
407 self.end.set(new_end);
415 pub fn alloc_raw(&self, layout: Layout) -> *mut u8 {
416 assert!(layout.size() != 0);
418 if let Some(a) = self.alloc_raw_without_grow(layout) {
421 // No free space left. Allocate a new chunk to satisfy the request.
422 // On failure the grow will panic or abort.
423 self.grow(layout.size());
428 pub fn alloc<T>(&self, object: T) -> &mut T {
429 assert!(!mem::needs_drop::<T>());
431 let mem = self.alloc_raw(Layout::for_value::<T>(&object)) as *mut T;
434 // Write into uninitialized memory.
435 ptr::write(mem, object);
440 /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
441 /// reference to it. Will panic if passed a zero-sized type.
445 /// - Zero-sized types
446 /// - Zero-length slices
448 pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
452 assert!(!mem::needs_drop::<T>());
453 assert!(mem::size_of::<T>() != 0);
454 assert!(!slice.is_empty());
456 let mem = self.alloc_raw(Layout::for_value::<[T]>(slice)) as *mut T;
459 mem.copy_from_nonoverlapping(slice.as_ptr(), slice.len());
460 slice::from_raw_parts_mut(mem, slice.len())
465 unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
472 // Use a manual loop since LLVM manages to optimize it better for
475 let value = iter.next();
476 if i >= len || value.is_none() {
477 // We only return as many items as the iterator gave us, even
478 // though it was supposed to give us `len`
479 return slice::from_raw_parts_mut(mem, i);
481 ptr::write(mem.add(i), value.unwrap());
487 pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
488 let iter = iter.into_iter();
489 assert!(mem::size_of::<T>() != 0);
490 assert!(!mem::needs_drop::<T>());
492 let size_hint = iter.size_hint();
495 (min, Some(max)) if min == max => {
496 // We know the exact number of elements the iterator will produce here
503 let mem = self.alloc_raw(Layout::array::<T>(len).unwrap()) as *mut T;
504 unsafe { self.write_from_iter(iter, len, mem) }
507 cold_path(move || -> &mut [T] {
508 let mut vec: SmallVec<[_; 8]> = iter.collect();
512 // Move the content to the arena by copying it and then forgetting
513 // the content of the SmallVec
517 self.alloc_raw(Layout::for_value::<[T]>(vec.as_slice())) as *mut T;
518 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
520 slice::from_raw_parts_mut(start_ptr, len)
528 /// Declare an `Arena` containing one dropless arena and many typed arenas (the
529 /// types of the typed arenas are specified by the arguments).
531 /// There are three cases of interest.
532 /// - Types that are `Copy`: these need not be specified in the arguments. They
533 /// will use the `DroplessArena`.
534 /// - Types that are `!Copy` and `!Drop`: these must be specified in the
535 /// arguments. An empty `TypedArena` will be created for each one, but the
536 /// `DroplessArena` will always be used and the `TypedArena` will stay empty.
537 /// This is odd but harmless, because an empty arena allocates no memory.
538 /// - Types that are `!Copy` and `Drop`: these must be specified in the
539 /// arguments. The `TypedArena` will be used for them.
541 #[rustc_macro_transparency = "semitransparent"]
542 pub macro declare_arena([$($a:tt $name:ident: $ty:ty,)*]) {
544 pub struct Arena<'tcx> {
545 pub dropless: $crate::DroplessArena,
546 $($name: $crate::TypedArena<$ty>,)*
549 pub trait ArenaAllocatable<'tcx, C = rustc_arena::IsNotCopy>: Sized {
550 fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self;
551 fn allocate_from_iter<'a>(
552 arena: &'a Arena<'tcx>,
553 iter: impl ::std::iter::IntoIterator<Item = Self>,
557 // Any type that impls `Copy` can be arena-allocated in the `DroplessArena`.
558 impl<'tcx, T: Copy> ArenaAllocatable<'tcx, rustc_arena::IsCopy> for T {
560 fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
561 arena.dropless.alloc(self)
564 fn allocate_from_iter<'a>(
565 arena: &'a Arena<'tcx>,
566 iter: impl ::std::iter::IntoIterator<Item = Self>,
567 ) -> &'a mut [Self] {
568 arena.dropless.alloc_from_iter(iter)
572 impl<'tcx> ArenaAllocatable<'tcx, rustc_arena::IsNotCopy> for $ty {
574 fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
575 if !::std::mem::needs_drop::<Self>() {
576 arena.dropless.alloc(self)
578 arena.$name.alloc(self)
583 fn allocate_from_iter<'a>(
584 arena: &'a Arena<'tcx>,
585 iter: impl ::std::iter::IntoIterator<Item = Self>,
586 ) -> &'a mut [Self] {
587 if !::std::mem::needs_drop::<Self>() {
588 arena.dropless.alloc_from_iter(iter)
590 arena.$name.alloc_from_iter(iter)
596 impl<'tcx> Arena<'tcx> {
598 pub fn alloc<T: ArenaAllocatable<'tcx, C>, C>(&self, value: T) -> &mut T {
599 value.allocate_on(self)
602 // Any type that impls `Copy` can have slices be arena-allocated in the `DroplessArena`.
604 pub fn alloc_slice<T: ::std::marker::Copy>(&self, value: &[T]) -> &mut [T] {
605 if value.is_empty() {
608 self.dropless.alloc_slice(value)
611 pub fn alloc_from_iter<'a, T: ArenaAllocatable<'tcx, C>, C>(
613 iter: impl ::std::iter::IntoIterator<Item = T>,
615 T::allocate_from_iter(self, iter)
620 // Marker types that let us give different behaviour for arenas allocating
621 // `Copy` types vs `!Copy` types.
623 pub struct IsNotCopy;