]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_arena/src/lib.rs
Rollup merge of #100030 - WaffleLapkin:nice_pointer_sis, r=scottmcm
[rust.git] / compiler / rustc_arena / src / lib.rs
1 //! The arena, a fast but limited type of allocator.
2 //!
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.
7 //!
8 //! This crate implements several kinds of arena.
9
10 #![doc(
11     html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
12     test(no_crate_inject, attr(deny(warnings)))
13 )]
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
23 use smallvec::SmallVec;
24
25 use std::alloc::Layout;
26 use std::cell::{Cell, RefCell};
27 use std::cmp;
28 use std::marker::{PhantomData, Send};
29 use std::mem::{self, MaybeUninit};
30 use std::ptr::{self, NonNull};
31 use std::slice;
32
33 #[inline(never)]
34 #[cold]
35 fn cold_path<F: FnOnce() -> R, R>(f: F) -> R {
36     f()
37 }
38
39 /// An arena that can hold objects of only one type.
40 pub struct TypedArena<T> {
41     /// A pointer to the next object to be allocated.
42     ptr: Cell<*mut T>,
43
44     /// A pointer to the end of the allocated area. When this pointer is
45     /// reached, a new chunk is allocated.
46     end: Cell<*mut T>,
47
48     /// A vector of arena chunks.
49     chunks: RefCell<Vec<ArenaChunk<T>>>,
50
51     /// Marker indicating that dropping the arena causes its owned
52     /// instances of `T` to be dropped.
53     _own: PhantomData<T>,
54 }
55
56 struct ArenaChunk<T = u8> {
57     /// The raw storage for the arena chunk.
58     storage: NonNull<[MaybeUninit<T>]>,
59     /// The number of valid entries in the chunk.
60     entries: usize,
61 }
62
63 unsafe impl<#[may_dangle] T> Drop for ArenaChunk<T> {
64     fn drop(&mut self) {
65         unsafe { Box::from_raw(self.storage.as_mut()) };
66     }
67 }
68
69 impl<T> ArenaChunk<T> {
70     #[inline]
71     unsafe fn new(capacity: usize) -> ArenaChunk<T> {
72         ArenaChunk {
73             storage: NonNull::new(Box::into_raw(Box::new_uninit_slice(capacity))).unwrap(),
74             entries: 0,
75         }
76     }
77
78     /// Destroys this arena chunk.
79     #[inline]
80     unsafe fn destroy(&mut self, len: usize) {
81         // The branch on needs_drop() is an -O1 performance optimization.
82         // Without the branch, dropping TypedArena<u8> takes linear time.
83         if mem::needs_drop::<T>() {
84             let slice = &mut *(self.storage.as_mut());
85             ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(&mut slice[..len]));
86         }
87     }
88
89     // Returns a pointer to the first allocated object.
90     #[inline]
91     fn start(&mut self) -> *mut T {
92         self.storage.as_ptr() as *mut T
93     }
94
95     // Returns a pointer to the end of the allocated space.
96     #[inline]
97     fn end(&mut self) -> *mut T {
98         unsafe {
99             if mem::size_of::<T>() == 0 {
100                 // A pointer as large as possible for zero-sized elements.
101                 ptr::invalid_mut(!0)
102             } else {
103                 self.start().add((*self.storage.as_ptr()).len())
104             }
105         }
106     }
107 }
108
109 // The arenas start with PAGE-sized chunks, and then each new chunk is twice as
110 // big as its predecessor, up until we reach HUGE_PAGE-sized chunks, whereupon
111 // we stop growing. This scales well, from arenas that are barely used up to
112 // arenas that are used for 100s of MiBs. Note also that the chosen sizes match
113 // the usual sizes of pages and huge pages on Linux.
114 const PAGE: usize = 4096;
115 const HUGE_PAGE: usize = 2 * 1024 * 1024;
116
117 impl<T> Default for TypedArena<T> {
118     /// Creates a new `TypedArena`.
119     fn default() -> TypedArena<T> {
120         TypedArena {
121             // We set both `ptr` and `end` to 0 so that the first call to
122             // alloc() will trigger a grow().
123             ptr: Cell::new(ptr::null_mut()),
124             end: Cell::new(ptr::null_mut()),
125             chunks: Default::default(),
126             _own: PhantomData,
127         }
128     }
129 }
130
131 trait IterExt<T> {
132     fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T];
133 }
134
135 impl<I, T> IterExt<T> for I
136 where
137     I: IntoIterator<Item = T>,
138 {
139     // This default collects into a `SmallVec` and then allocates by copying
140     // from it. The specializations below for types like `Vec` are more
141     // efficient, copying directly without the intermediate collecting step.
142     // This default could be made more efficient, like
143     // `DroplessArena::alloc_from_iter`, but it's not hot enough to bother.
144     #[inline]
145     default fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
146         let vec: SmallVec<[_; 8]> = self.into_iter().collect();
147         vec.alloc_from_iter(arena)
148     }
149 }
150
151 impl<T, const N: usize> IterExt<T> for std::array::IntoIter<T, N> {
152     #[inline]
153     fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
154         let len = self.len();
155         if len == 0 {
156             return &mut [];
157         }
158         // Move the content to the arena by copying and then forgetting it.
159         unsafe {
160             let start_ptr = arena.alloc_raw_slice(len);
161             self.as_slice().as_ptr().copy_to_nonoverlapping(start_ptr, len);
162             mem::forget(self);
163             slice::from_raw_parts_mut(start_ptr, len)
164         }
165     }
166 }
167
168 impl<T> IterExt<T> for Vec<T> {
169     #[inline]
170     fn alloc_from_iter(mut self, arena: &TypedArena<T>) -> &mut [T] {
171         let len = self.len();
172         if len == 0 {
173             return &mut [];
174         }
175         // Move the content to the arena by copying and then forgetting it.
176         unsafe {
177             let start_ptr = arena.alloc_raw_slice(len);
178             self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
179             self.set_len(0);
180             slice::from_raw_parts_mut(start_ptr, len)
181         }
182     }
183 }
184
185 impl<A: smallvec::Array> IterExt<A::Item> for SmallVec<A> {
186     #[inline]
187     fn alloc_from_iter(mut self, arena: &TypedArena<A::Item>) -> &mut [A::Item] {
188         let len = self.len();
189         if len == 0 {
190             return &mut [];
191         }
192         // Move the content to the arena by copying and then forgetting it.
193         unsafe {
194             let start_ptr = arena.alloc_raw_slice(len);
195             self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
196             self.set_len(0);
197             slice::from_raw_parts_mut(start_ptr, len)
198         }
199     }
200 }
201
202 impl<T> TypedArena<T> {
203     /// Allocates an object in the `TypedArena`, returning a reference to it.
204     #[inline]
205     pub fn alloc(&self, object: T) -> &mut T {
206         if self.ptr == self.end {
207             self.grow(1)
208         }
209
210         unsafe {
211             if mem::size_of::<T>() == 0 {
212                 self.ptr.set((self.ptr.get() as *mut u8).wrapping_offset(1) as *mut T);
213                 let ptr = ptr::NonNull::<T>::dangling().as_ptr();
214                 // Don't drop the object. This `write` is equivalent to `forget`.
215                 ptr::write(ptr, object);
216                 &mut *ptr
217             } else {
218                 let ptr = self.ptr.get();
219                 // Advance the pointer.
220                 self.ptr.set(self.ptr.get().offset(1));
221                 // Write into uninitialized memory.
222                 ptr::write(ptr, object);
223                 &mut *ptr
224             }
225         }
226     }
227
228     #[inline]
229     fn can_allocate(&self, additional: usize) -> bool {
230         // FIXME: this should *likely* use `offset_from`, but more
231         // investigation is needed (including running tests in miri).
232         let available_bytes = self.end.get().addr() - self.ptr.get().addr();
233         let additional_bytes = additional.checked_mul(mem::size_of::<T>()).unwrap();
234         available_bytes >= additional_bytes
235     }
236
237     /// Ensures there's enough space in the current chunk to fit `len` objects.
238     #[inline]
239     fn ensure_capacity(&self, additional: usize) {
240         if !self.can_allocate(additional) {
241             self.grow(additional);
242             debug_assert!(self.can_allocate(additional));
243         }
244     }
245
246     #[inline]
247     unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
248         assert!(mem::size_of::<T>() != 0);
249         assert!(len != 0);
250
251         self.ensure_capacity(len);
252
253         let start_ptr = self.ptr.get();
254         self.ptr.set(start_ptr.add(len));
255         start_ptr
256     }
257
258     #[inline]
259     pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
260         assert!(mem::size_of::<T>() != 0);
261         iter.alloc_from_iter(self)
262     }
263
264     /// Grows the arena.
265     #[inline(never)]
266     #[cold]
267     fn grow(&self, additional: usize) {
268         unsafe {
269             // We need the element size to convert chunk sizes (ranging from
270             // PAGE to HUGE_PAGE bytes) to element counts.
271             let elem_size = cmp::max(1, mem::size_of::<T>());
272             let mut chunks = self.chunks.borrow_mut();
273             let mut new_cap;
274             if let Some(last_chunk) = chunks.last_mut() {
275                 // If a type is `!needs_drop`, we don't need to keep track of how many elements
276                 // the chunk stores - the field will be ignored anyway.
277                 if mem::needs_drop::<T>() {
278                     // FIXME: this should *likely* use `offset_from`, but more
279                     // investigation is needed (including running tests in miri).
280                     let used_bytes = self.ptr.get().addr() - last_chunk.start().addr();
281                     last_chunk.entries = used_bytes / mem::size_of::<T>();
282                 }
283
284                 // If the previous chunk's len is less than HUGE_PAGE
285                 // bytes, then this chunk will be least double the previous
286                 // chunk's size.
287                 new_cap = (*last_chunk.storage.as_ptr()).len().min(HUGE_PAGE / elem_size / 2);
288                 new_cap *= 2;
289             } else {
290                 new_cap = PAGE / elem_size;
291             }
292             // Also ensure that this chunk can fit `additional`.
293             new_cap = cmp::max(additional, new_cap);
294
295             let mut chunk = ArenaChunk::<T>::new(new_cap);
296             self.ptr.set(chunk.start());
297             self.end.set(chunk.end());
298             chunks.push(chunk);
299         }
300     }
301
302     // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
303     // chunks.
304     fn clear_last_chunk(&self, last_chunk: &mut ArenaChunk<T>) {
305         // Determine how much was filled.
306         let start = last_chunk.start().addr();
307         // We obtain the value of the pointer to the first uninitialized element.
308         let end = self.ptr.get().addr();
309         // We then calculate the number of elements to be dropped in the last chunk,
310         // which is the filled area's length.
311         let diff = if mem::size_of::<T>() == 0 {
312             // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
313             // the number of zero-sized values in the last and only chunk, just out of caution.
314             // Recall that `end` was incremented for each allocated value.
315             end - start
316         } else {
317             // FIXME: this should *likely* use `offset_from`, but more
318             // investigation is needed (including running tests in miri).
319             (end - start) / mem::size_of::<T>()
320         };
321         // Pass that to the `destroy` method.
322         unsafe {
323             last_chunk.destroy(diff);
324         }
325         // Reset the chunk.
326         self.ptr.set(last_chunk.start());
327     }
328 }
329
330 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
331     fn drop(&mut self) {
332         unsafe {
333             // Determine how much was filled.
334             let mut chunks_borrow = self.chunks.borrow_mut();
335             if let Some(mut last_chunk) = chunks_borrow.pop() {
336                 // Drop the contents of the last chunk.
337                 self.clear_last_chunk(&mut last_chunk);
338                 // The last chunk will be dropped. Destroy all other chunks.
339                 for chunk in chunks_borrow.iter_mut() {
340                     chunk.destroy(chunk.entries);
341                 }
342             }
343             // Box handles deallocation of `last_chunk` and `self.chunks`.
344         }
345     }
346 }
347
348 unsafe impl<T: Send> Send for TypedArena<T> {}
349
350 /// An arena that can hold objects of multiple different types that impl `Copy`
351 /// and/or satisfy `!mem::needs_drop`.
352 pub struct DroplessArena {
353     /// A pointer to the start of the free space.
354     start: Cell<*mut u8>,
355
356     /// A pointer to the end of free space.
357     ///
358     /// The allocation proceeds downwards from the end of the chunk towards the
359     /// start. (This is slightly simpler and faster than allocating upwards,
360     /// see <https://fitzgeraldnick.com/2019/11/01/always-bump-downwards.html>.)
361     /// When this pointer crosses the start pointer, a new chunk is allocated.
362     end: Cell<*mut u8>,
363
364     /// A vector of arena chunks.
365     chunks: RefCell<Vec<ArenaChunk>>,
366 }
367
368 unsafe impl Send for DroplessArena {}
369
370 impl Default for DroplessArena {
371     #[inline]
372     fn default() -> DroplessArena {
373         DroplessArena {
374             start: Cell::new(ptr::null_mut()),
375             end: Cell::new(ptr::null_mut()),
376             chunks: Default::default(),
377         }
378     }
379 }
380
381 impl DroplessArena {
382     #[inline(never)]
383     #[cold]
384     fn grow(&self, additional: usize) {
385         unsafe {
386             let mut chunks = self.chunks.borrow_mut();
387             let mut new_cap;
388             if let Some(last_chunk) = chunks.last_mut() {
389                 // There is no need to update `last_chunk.entries` because that
390                 // field isn't used by `DroplessArena`.
391
392                 // If the previous chunk's len is less than HUGE_PAGE
393                 // bytes, then this chunk will be least double the previous
394                 // chunk's size.
395                 new_cap = (*last_chunk.storage.as_ptr()).len().min(HUGE_PAGE / 2);
396                 new_cap *= 2;
397             } else {
398                 new_cap = PAGE;
399             }
400             // Also ensure that this chunk can fit `additional`.
401             new_cap = cmp::max(additional, new_cap);
402
403             let mut chunk = ArenaChunk::new(new_cap);
404             self.start.set(chunk.start());
405             self.end.set(chunk.end());
406             chunks.push(chunk);
407         }
408     }
409
410     /// Allocates a byte slice with specified layout from the current memory
411     /// chunk. Returns `None` if there is no free space left to satisfy the
412     /// request.
413     #[inline]
414     fn alloc_raw_without_grow(&self, layout: Layout) -> Option<*mut u8> {
415         let start = self.start.get().addr();
416         let old_end = self.end.get();
417         let end = old_end.addr();
418
419         let align = layout.align();
420         let bytes = layout.size();
421
422         let new_end = end.checked_sub(bytes)? & !(align - 1);
423         if start <= new_end {
424             let new_end = old_end.with_addr(new_end);
425             self.end.set(new_end);
426             Some(new_end)
427         } else {
428             None
429         }
430     }
431
432     #[inline]
433     pub fn alloc_raw(&self, layout: Layout) -> *mut u8 {
434         assert!(layout.size() != 0);
435         loop {
436             if let Some(a) = self.alloc_raw_without_grow(layout) {
437                 break a;
438             }
439             // No free space left. Allocate a new chunk to satisfy the request.
440             // On failure the grow will panic or abort.
441             self.grow(layout.size());
442         }
443     }
444
445     #[inline]
446     pub fn alloc<T>(&self, object: T) -> &mut T {
447         assert!(!mem::needs_drop::<T>());
448
449         let mem = self.alloc_raw(Layout::for_value::<T>(&object)) as *mut T;
450
451         unsafe {
452             // Write into uninitialized memory.
453             ptr::write(mem, object);
454             &mut *mem
455         }
456     }
457
458     /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
459     /// reference to it. Will panic if passed a zero-sized type.
460     ///
461     /// Panics:
462     ///
463     ///  - Zero-sized types
464     ///  - Zero-length slices
465     #[inline]
466     pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
467     where
468         T: Copy,
469     {
470         assert!(!mem::needs_drop::<T>());
471         assert!(mem::size_of::<T>() != 0);
472         assert!(!slice.is_empty());
473
474         let mem = self.alloc_raw(Layout::for_value::<[T]>(slice)) as *mut T;
475
476         unsafe {
477             mem.copy_from_nonoverlapping(slice.as_ptr(), slice.len());
478             slice::from_raw_parts_mut(mem, slice.len())
479         }
480     }
481
482     #[inline]
483     unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
484         &self,
485         mut iter: I,
486         len: usize,
487         mem: *mut T,
488     ) -> &mut [T] {
489         let mut i = 0;
490         // Use a manual loop since LLVM manages to optimize it better for
491         // slice iterators
492         loop {
493             let value = iter.next();
494             if i >= len || value.is_none() {
495                 // We only return as many items as the iterator gave us, even
496                 // though it was supposed to give us `len`
497                 return slice::from_raw_parts_mut(mem, i);
498             }
499             ptr::write(mem.add(i), value.unwrap());
500             i += 1;
501         }
502     }
503
504     #[inline]
505     pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
506         let iter = iter.into_iter();
507         assert!(mem::size_of::<T>() != 0);
508         assert!(!mem::needs_drop::<T>());
509
510         let size_hint = iter.size_hint();
511
512         match size_hint {
513             (min, Some(max)) if min == max => {
514                 // We know the exact number of elements the iterator will produce here
515                 let len = min;
516
517                 if len == 0 {
518                     return &mut [];
519                 }
520
521                 let mem = self.alloc_raw(Layout::array::<T>(len).unwrap()) as *mut T;
522                 unsafe { self.write_from_iter(iter, len, mem) }
523             }
524             (_, _) => {
525                 cold_path(move || -> &mut [T] {
526                     let mut vec: SmallVec<[_; 8]> = iter.collect();
527                     if vec.is_empty() {
528                         return &mut [];
529                     }
530                     // Move the content to the arena by copying it and then forgetting
531                     // the content of the SmallVec
532                     unsafe {
533                         let len = vec.len();
534                         let start_ptr =
535                             self.alloc_raw(Layout::for_value::<[T]>(vec.as_slice())) as *mut T;
536                         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
537                         vec.set_len(0);
538                         slice::from_raw_parts_mut(start_ptr, len)
539                     }
540                 })
541             }
542         }
543     }
544 }
545
546 /// Declare an `Arena` containing one dropless arena and many typed arenas (the
547 /// types of the typed arenas are specified by the arguments).
548 ///
549 /// There are three cases of interest.
550 /// - Types that are `Copy`: these need not be specified in the arguments. They
551 ///   will use the `DroplessArena`.
552 /// - Types that are `!Copy` and `!Drop`: these must be specified in the
553 ///   arguments. An empty `TypedArena` will be created for each one, but the
554 ///   `DroplessArena` will always be used and the `TypedArena` will stay empty.
555 ///   This is odd but harmless, because an empty arena allocates no memory.
556 /// - Types that are `!Copy` and `Drop`: these must be specified in the
557 ///   arguments. The `TypedArena` will be used for them.
558 ///
559 #[rustc_macro_transparency = "semitransparent"]
560 pub macro declare_arena([$($a:tt $name:ident: $ty:ty,)*]) {
561     #[derive(Default)]
562     pub struct Arena<'tcx> {
563         pub dropless: $crate::DroplessArena,
564         $($name: $crate::TypedArena<$ty>,)*
565     }
566
567     pub trait ArenaAllocatable<'tcx, C = rustc_arena::IsNotCopy>: Sized {
568         fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self;
569         fn allocate_from_iter<'a>(
570             arena: &'a Arena<'tcx>,
571             iter: impl ::std::iter::IntoIterator<Item = Self>,
572         ) -> &'a mut [Self];
573     }
574
575     // Any type that impls `Copy` can be arena-allocated in the `DroplessArena`.
576     impl<'tcx, T: Copy> ArenaAllocatable<'tcx, rustc_arena::IsCopy> for T {
577         #[inline]
578         fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
579             arena.dropless.alloc(self)
580         }
581         #[inline]
582         fn allocate_from_iter<'a>(
583             arena: &'a Arena<'tcx>,
584             iter: impl ::std::iter::IntoIterator<Item = Self>,
585         ) -> &'a mut [Self] {
586             arena.dropless.alloc_from_iter(iter)
587         }
588     }
589     $(
590         impl<'tcx> ArenaAllocatable<'tcx, rustc_arena::IsNotCopy> for $ty {
591             #[inline]
592             fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
593                 if !::std::mem::needs_drop::<Self>() {
594                     arena.dropless.alloc(self)
595                 } else {
596                     arena.$name.alloc(self)
597                 }
598             }
599
600             #[inline]
601             fn allocate_from_iter<'a>(
602                 arena: &'a Arena<'tcx>,
603                 iter: impl ::std::iter::IntoIterator<Item = Self>,
604             ) -> &'a mut [Self] {
605                 if !::std::mem::needs_drop::<Self>() {
606                     arena.dropless.alloc_from_iter(iter)
607                 } else {
608                     arena.$name.alloc_from_iter(iter)
609                 }
610             }
611         }
612     )*
613
614     impl<'tcx> Arena<'tcx> {
615         #[inline]
616         pub fn alloc<T: ArenaAllocatable<'tcx, C>, C>(&self, value: T) -> &mut T {
617             value.allocate_on(self)
618         }
619
620         // Any type that impls `Copy` can have slices be arena-allocated in the `DroplessArena`.
621         #[inline]
622         pub fn alloc_slice<T: ::std::marker::Copy>(&self, value: &[T]) -> &mut [T] {
623             if value.is_empty() {
624                 return &mut [];
625             }
626             self.dropless.alloc_slice(value)
627         }
628
629         pub fn alloc_from_iter<'a, T: ArenaAllocatable<'tcx, C>, C>(
630             &'a self,
631             iter: impl ::std::iter::IntoIterator<Item = T>,
632         ) -> &'a mut [T] {
633             T::allocate_from_iter(self, iter)
634         }
635     }
636 }
637
638 // Marker types that let us give different behaviour for arenas allocating
639 // `Copy` types vs `!Copy` types.
640 pub struct IsCopy;
641 pub struct IsNotCopy;
642
643 #[cfg(test)]
644 mod tests;