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))]
21 #![feature(strict_provenance)]
22 #![feature(ptr_const_cast)]
24 use smallvec::SmallVec;
26 use std::alloc::Layout;
27 use std::cell::{Cell, RefCell};
29 use std::marker::{PhantomData, Send};
30 use std::mem::{self, MaybeUninit};
31 use std::ptr::{self, NonNull};
36 fn cold_path<F: FnOnce() -> R, R>(f: F) -> R {
40 /// An arena that can hold objects of only one type.
41 pub struct TypedArena<T> {
42 /// A pointer to the next object to be allocated.
45 /// A pointer to the end of the allocated area. When this pointer is
46 /// reached, a new chunk is allocated.
49 /// A vector of arena chunks.
50 chunks: RefCell<Vec<ArenaChunk<T>>>,
52 /// Marker indicating that dropping the arena causes its owned
53 /// instances of `T` to be dropped.
57 struct ArenaChunk<T = u8> {
58 /// The raw storage for the arena chunk.
59 storage: NonNull<[MaybeUninit<T>]>,
60 /// The number of valid entries in the chunk.
64 unsafe impl<#[may_dangle] T> Drop for ArenaChunk<T> {
66 unsafe { Box::from_raw(self.storage.as_mut()) };
70 impl<T> ArenaChunk<T> {
72 unsafe fn new(capacity: usize) -> ArenaChunk<T> {
74 storage: NonNull::new(Box::into_raw(Box::new_uninit_slice(capacity))).unwrap(),
79 /// Destroys this arena chunk.
81 unsafe fn destroy(&mut self, len: usize) {
82 // The branch on needs_drop() is an -O1 performance optimization.
83 // Without the branch, dropping TypedArena<u8> takes linear time.
84 if mem::needs_drop::<T>() {
85 let slice = &mut *(self.storage.as_mut());
86 ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(&mut slice[..len]));
90 // Returns a pointer to the first allocated object.
92 fn start(&mut self) -> *mut T {
93 self.storage.as_ptr() as *mut T
96 // Returns a pointer to the end of the allocated space.
98 fn end(&mut self) -> *mut T {
100 if mem::size_of::<T>() == 0 {
101 // A pointer as large as possible for zero-sized elements.
104 self.start().add((*self.storage.as_ptr()).len())
110 // The arenas start with PAGE-sized chunks, and then each new chunk is twice as
111 // big as its predecessor, up until we reach HUGE_PAGE-sized chunks, whereupon
112 // we stop growing. This scales well, from arenas that are barely used up to
113 // arenas that are used for 100s of MiBs. Note also that the chosen sizes match
114 // the usual sizes of pages and huge pages on Linux.
115 const PAGE: usize = 4096;
116 const HUGE_PAGE: usize = 2 * 1024 * 1024;
118 impl<T> Default for TypedArena<T> {
119 /// Creates a new `TypedArena`.
120 fn default() -> TypedArena<T> {
122 // We set both `ptr` and `end` to 0 so that the first call to
123 // alloc() will trigger a grow().
124 ptr: Cell::new(ptr::null_mut()),
125 end: Cell::new(ptr::null_mut()),
126 chunks: Default::default(),
133 fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T];
136 impl<I, T> IterExt<T> for I
138 I: IntoIterator<Item = T>,
140 // This default collects into a `SmallVec` and then allocates by copying
141 // from it. The specializations below for types like `Vec` are more
142 // efficient, copying directly without the intermediate collecting step.
143 // This default could be made more efficient, like
144 // `DroplessArena::alloc_from_iter`, but it's not hot enough to bother.
146 default fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
147 let vec: SmallVec<[_; 8]> = self.into_iter().collect();
148 vec.alloc_from_iter(arena)
152 impl<T, const N: usize> IterExt<T> for std::array::IntoIter<T, N> {
154 fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
155 let len = self.len();
159 // Move the content to the arena by copying and then forgetting it.
161 let start_ptr = arena.alloc_raw_slice(len);
162 self.as_slice().as_ptr().copy_to_nonoverlapping(start_ptr, len);
164 slice::from_raw_parts_mut(start_ptr, len)
169 impl<T> IterExt<T> for Vec<T> {
171 fn alloc_from_iter(mut self, arena: &TypedArena<T>) -> &mut [T] {
172 let len = self.len();
176 // Move the content to the arena by copying and then forgetting it.
178 let start_ptr = arena.alloc_raw_slice(len);
179 self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
181 slice::from_raw_parts_mut(start_ptr, len)
186 impl<A: smallvec::Array> IterExt<A::Item> for SmallVec<A> {
188 fn alloc_from_iter(mut self, arena: &TypedArena<A::Item>) -> &mut [A::Item] {
189 let len = self.len();
193 // Move the content to the arena by copying and then forgetting it.
195 let start_ptr = arena.alloc_raw_slice(len);
196 self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
198 slice::from_raw_parts_mut(start_ptr, len)
203 impl<T> TypedArena<T> {
204 /// Allocates an object in the `TypedArena`, returning a reference to it.
206 pub fn alloc(&self, object: T) -> &mut T {
207 if self.ptr == self.end {
212 if mem::size_of::<T>() == 0 {
213 self.ptr.set((self.ptr.get() as *mut u8).wrapping_offset(1) as *mut T);
214 let ptr = ptr::NonNull::<T>::dangling().as_ptr();
215 // Don't drop the object. This `write` is equivalent to `forget`.
216 ptr::write(ptr, object);
219 let ptr = self.ptr.get();
220 // Advance the pointer.
221 self.ptr.set(self.ptr.get().offset(1));
222 // Write into uninitialized memory.
223 ptr::write(ptr, object);
230 fn can_allocate(&self, additional: usize) -> bool {
231 // FIXME: this should *likely* use `offset_from`, but more
232 // investigation is needed (including running tests in miri).
233 let available_bytes = self.end.get().addr() - self.ptr.get().addr();
234 let additional_bytes = additional.checked_mul(mem::size_of::<T>()).unwrap();
235 available_bytes >= additional_bytes
238 /// Ensures there's enough space in the current chunk to fit `len` objects.
240 fn ensure_capacity(&self, additional: usize) {
241 if !self.can_allocate(additional) {
242 self.grow(additional);
243 debug_assert!(self.can_allocate(additional));
248 unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
249 assert!(mem::size_of::<T>() != 0);
252 self.ensure_capacity(len);
254 let start_ptr = self.ptr.get();
255 self.ptr.set(start_ptr.add(len));
260 pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
261 assert!(mem::size_of::<T>() != 0);
262 iter.alloc_from_iter(self)
268 fn grow(&self, additional: usize) {
270 // We need the element size to convert chunk sizes (ranging from
271 // PAGE to HUGE_PAGE bytes) to element counts.
272 let elem_size = cmp::max(1, mem::size_of::<T>());
273 let mut chunks = self.chunks.borrow_mut();
275 if let Some(last_chunk) = chunks.last_mut() {
276 // If a type is `!needs_drop`, we don't need to keep track of how many elements
277 // the chunk stores - the field will be ignored anyway.
278 if mem::needs_drop::<T>() {
279 // FIXME: this should *likely* use `offset_from`, but more
280 // investigation is needed (including running tests in miri).
281 let used_bytes = self.ptr.get().addr() - last_chunk.start().addr();
282 last_chunk.entries = used_bytes / mem::size_of::<T>();
285 // If the previous chunk's len is less than HUGE_PAGE
286 // bytes, then this chunk will be least double the previous
288 new_cap = (*last_chunk.storage.as_ptr()).len().min(HUGE_PAGE / elem_size / 2);
291 new_cap = PAGE / elem_size;
293 // Also ensure that this chunk can fit `additional`.
294 new_cap = cmp::max(additional, new_cap);
296 let mut chunk = ArenaChunk::<T>::new(new_cap);
297 self.ptr.set(chunk.start());
298 self.end.set(chunk.end());
303 // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
305 fn clear_last_chunk(&self, last_chunk: &mut ArenaChunk<T>) {
306 // Determine how much was filled.
307 let start = last_chunk.start().addr();
308 // We obtain the value of the pointer to the first uninitialized element.
309 let end = self.ptr.get().addr();
310 // We then calculate the number of elements to be dropped in the last chunk,
311 // which is the filled area's length.
312 let diff = if mem::size_of::<T>() == 0 {
313 // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
314 // the number of zero-sized values in the last and only chunk, just out of caution.
315 // Recall that `end` was incremented for each allocated value.
318 // FIXME: this should *likely* use `offset_from`, but more
319 // investigation is needed (including running tests in miri).
320 (end - start) / mem::size_of::<T>()
322 // Pass that to the `destroy` method.
324 last_chunk.destroy(diff);
327 self.ptr.set(last_chunk.start());
331 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
334 // Determine how much was filled.
335 let mut chunks_borrow = self.chunks.borrow_mut();
336 if let Some(mut last_chunk) = chunks_borrow.pop() {
337 // Drop the contents of the last chunk.
338 self.clear_last_chunk(&mut last_chunk);
339 // The last chunk will be dropped. Destroy all other chunks.
340 for chunk in chunks_borrow.iter_mut() {
341 chunk.destroy(chunk.entries);
344 // Box handles deallocation of `last_chunk` and `self.chunks`.
349 unsafe impl<T: Send> Send for TypedArena<T> {}
351 /// An arena that can hold objects of multiple different types that impl `Copy`
352 /// and/or satisfy `!mem::needs_drop`.
353 pub struct DroplessArena {
354 /// A pointer to the start of the free space.
355 start: Cell<*mut u8>,
357 /// A pointer to the end of free space.
359 /// The allocation proceeds downwards from the end of the chunk towards the
360 /// start. (This is slightly simpler and faster than allocating upwards,
361 /// see <https://fitzgeraldnick.com/2019/11/01/always-bump-downwards.html>.)
362 /// When this pointer crosses the start pointer, a new chunk is allocated.
365 /// A vector of arena chunks.
366 chunks: RefCell<Vec<ArenaChunk>>,
369 unsafe impl Send for DroplessArena {}
371 impl Default for DroplessArena {
373 fn default() -> DroplessArena {
375 start: Cell::new(ptr::null_mut()),
376 end: Cell::new(ptr::null_mut()),
377 chunks: Default::default(),
385 fn grow(&self, additional: usize) {
387 let mut chunks = self.chunks.borrow_mut();
389 if let Some(last_chunk) = chunks.last_mut() {
390 // There is no need to update `last_chunk.entries` because that
391 // field isn't used by `DroplessArena`.
393 // If the previous chunk's len is less than HUGE_PAGE
394 // bytes, then this chunk will be least double the previous
396 new_cap = (*last_chunk.storage.as_ptr()).len().min(HUGE_PAGE / 2);
401 // Also ensure that this chunk can fit `additional`.
402 new_cap = cmp::max(additional, new_cap);
404 let mut chunk = ArenaChunk::new(new_cap);
405 self.start.set(chunk.start());
406 self.end.set(chunk.end());
411 /// Allocates a byte slice with specified layout from the current memory
412 /// chunk. Returns `None` if there is no free space left to satisfy the
415 fn alloc_raw_without_grow(&self, layout: Layout) -> Option<*mut u8> {
416 let start = self.start.get().addr();
417 let old_end = self.end.get();
418 let end = old_end.addr();
420 let align = layout.align();
421 let bytes = layout.size();
423 let new_end = end.checked_sub(bytes)? & !(align - 1);
424 if start <= new_end {
425 let new_end = old_end.with_addr(new_end);
426 self.end.set(new_end);
434 pub fn alloc_raw(&self, layout: Layout) -> *mut u8 {
435 assert!(layout.size() != 0);
437 if let Some(a) = self.alloc_raw_without_grow(layout) {
440 // No free space left. Allocate a new chunk to satisfy the request.
441 // On failure the grow will panic or abort.
442 self.grow(layout.size());
447 pub fn alloc<T>(&self, object: T) -> &mut T {
448 assert!(!mem::needs_drop::<T>());
450 let mem = self.alloc_raw(Layout::for_value::<T>(&object)) as *mut T;
453 // Write into uninitialized memory.
454 ptr::write(mem, object);
459 /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
460 /// reference to it. Will panic if passed a zero-sized type.
464 /// - Zero-sized types
465 /// - Zero-length slices
467 pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
471 assert!(!mem::needs_drop::<T>());
472 assert!(mem::size_of::<T>() != 0);
473 assert!(!slice.is_empty());
475 let mem = self.alloc_raw(Layout::for_value::<[T]>(slice)) as *mut T;
478 mem.copy_from_nonoverlapping(slice.as_ptr(), slice.len());
479 slice::from_raw_parts_mut(mem, slice.len())
484 unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
491 // Use a manual loop since LLVM manages to optimize it better for
494 let value = iter.next();
495 if i >= len || value.is_none() {
496 // We only return as many items as the iterator gave us, even
497 // though it was supposed to give us `len`
498 return slice::from_raw_parts_mut(mem, i);
500 ptr::write(mem.add(i), value.unwrap());
506 pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
507 let iter = iter.into_iter();
508 assert!(mem::size_of::<T>() != 0);
509 assert!(!mem::needs_drop::<T>());
511 let size_hint = iter.size_hint();
514 (min, Some(max)) if min == max => {
515 // We know the exact number of elements the iterator will produce here
522 let mem = self.alloc_raw(Layout::array::<T>(len).unwrap()) as *mut T;
523 unsafe { self.write_from_iter(iter, len, mem) }
526 cold_path(move || -> &mut [T] {
527 let mut vec: SmallVec<[_; 8]> = iter.collect();
531 // Move the content to the arena by copying it and then forgetting
532 // the content of the SmallVec
536 self.alloc_raw(Layout::for_value::<[T]>(vec.as_slice())) as *mut T;
537 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
539 slice::from_raw_parts_mut(start_ptr, len)
547 /// Declare an `Arena` containing one dropless arena and many typed arenas (the
548 /// types of the typed arenas are specified by the arguments).
550 /// There are three cases of interest.
551 /// - Types that are `Copy`: these need not be specified in the arguments. They
552 /// will use the `DroplessArena`.
553 /// - Types that are `!Copy` and `!Drop`: these must be specified in the
554 /// arguments. An empty `TypedArena` will be created for each one, but the
555 /// `DroplessArena` will always be used and the `TypedArena` will stay empty.
556 /// This is odd but harmless, because an empty arena allocates no memory.
557 /// - Types that are `!Copy` and `Drop`: these must be specified in the
558 /// arguments. The `TypedArena` will be used for them.
560 #[rustc_macro_transparency = "semitransparent"]
561 pub macro declare_arena([$($a:tt $name:ident: $ty:ty,)*]) {
563 pub struct Arena<'tcx> {
564 pub dropless: $crate::DroplessArena,
565 $($name: $crate::TypedArena<$ty>,)*
568 pub trait ArenaAllocatable<'tcx, C = rustc_arena::IsNotCopy>: Sized {
569 fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self;
570 fn allocate_from_iter<'a>(
571 arena: &'a Arena<'tcx>,
572 iter: impl ::std::iter::IntoIterator<Item = Self>,
576 // Any type that impls `Copy` can be arena-allocated in the `DroplessArena`.
577 impl<'tcx, T: Copy> ArenaAllocatable<'tcx, rustc_arena::IsCopy> for T {
579 fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
580 arena.dropless.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 arena.dropless.alloc_from_iter(iter)
591 impl<'tcx> ArenaAllocatable<'tcx, rustc_arena::IsNotCopy> for $ty {
593 fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
594 if !::std::mem::needs_drop::<Self>() {
595 arena.dropless.alloc(self)
597 arena.$name.alloc(self)
602 fn allocate_from_iter<'a>(
603 arena: &'a Arena<'tcx>,
604 iter: impl ::std::iter::IntoIterator<Item = Self>,
605 ) -> &'a mut [Self] {
606 if !::std::mem::needs_drop::<Self>() {
607 arena.dropless.alloc_from_iter(iter)
609 arena.$name.alloc_from_iter(iter)
615 impl<'tcx> Arena<'tcx> {
617 pub fn alloc<T: ArenaAllocatable<'tcx, C>, C>(&self, value: T) -> &mut T {
618 value.allocate_on(self)
621 // Any type that impls `Copy` can have slices be arena-allocated in the `DroplessArena`.
623 pub fn alloc_slice<T: ::std::marker::Copy>(&self, value: &[T]) -> &mut [T] {
624 if value.is_empty() {
627 self.dropless.alloc_slice(value)
630 pub fn alloc_from_iter<'a, T: ArenaAllocatable<'tcx, C>, C>(
632 iter: impl ::std::iter::IntoIterator<Item = T>,
634 T::allocate_from_iter(self, iter)
639 // Marker types that let us give different behaviour for arenas allocating
640 // `Copy` types vs `!Copy` types.
642 pub struct IsNotCopy;