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