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