]> git.lizzy.rs Git - rust.git/blob - src/librustc/arena.rs
Rollup merge of #60581 - hellow554:fix_60580, r=alexcrichton
[rust.git] / src / librustc / arena.rs
1 use arena::{TypedArena, DroplessArena};
2 use std::mem;
3 use std::ptr;
4 use std::slice;
5 use std::cell::RefCell;
6 use std::marker::PhantomData;
7 use smallvec::SmallVec;
8
9 #[macro_export]
10 macro_rules! arena_types {
11     ($macro:path, $args:tt, $tcx:lifetime) => (
12         $macro!($args, [
13             [] vtable_method: Option<(
14                 rustc::hir::def_id::DefId,
15                 rustc::ty::subst::SubstsRef<$tcx>
16             )>,
17             [few] mir_keys: rustc::util::nodemap::DefIdSet,
18             [decode] specialization_graph: rustc::traits::specialization_graph::Graph,
19             [] region_scope_tree: rustc::middle::region::ScopeTree,
20             [] item_local_set: rustc::util::nodemap::ItemLocalSet,
21             [decode] mir_const_qualif: rustc_data_structures::bit_set::BitSet<rustc::mir::Local>,
22             [] trait_impls_of: rustc::ty::trait_def::TraitImpls,
23             [] dropck_outlives:
24                 rustc::infer::canonical::Canonical<'tcx,
25                     rustc::infer::canonical::QueryResponse<'tcx,
26                         rustc::traits::query::dropck_outlives::DropckOutlivesResult<'tcx>
27                     >
28                 >,
29             [] normalize_projection_ty:
30                 rustc::infer::canonical::Canonical<'tcx,
31                     rustc::infer::canonical::QueryResponse<'tcx,
32                         rustc::traits::query::normalize::NormalizationResult<'tcx>
33                     >
34                 >,
35             [] implied_outlives_bounds:
36                 rustc::infer::canonical::Canonical<'tcx,
37                     rustc::infer::canonical::QueryResponse<'tcx,
38                         Vec<rustc::traits::query::outlives_bounds::OutlivesBound<'tcx>>
39                     >
40                 >,
41             [] type_op_subtype:
42                 rustc::infer::canonical::Canonical<'tcx,
43                     rustc::infer::canonical::QueryResponse<'tcx, ()>
44                 >,
45             [] type_op_normalize_poly_fn_sig:
46                 rustc::infer::canonical::Canonical<'tcx,
47                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::PolyFnSig<'tcx>>
48                 >,
49             [] type_op_normalize_fn_sig:
50                 rustc::infer::canonical::Canonical<'tcx,
51                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::FnSig<'tcx>>
52                 >,
53             [] type_op_normalize_predicate:
54                 rustc::infer::canonical::Canonical<'tcx,
55                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Predicate<'tcx>>
56                 >,
57             [] type_op_normalize_ty:
58                 rustc::infer::canonical::Canonical<'tcx,
59                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Ty<'tcx>>
60                 >,
61         ], $tcx);
62     )
63 }
64
65 macro_rules! arena_for_type {
66     ([][$ty:ty]) => {
67         TypedArena<$ty>
68     };
69     ([few $(, $attrs:ident)*][$ty:ty]) => {
70         PhantomData<$ty>
71     };
72     ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
73         arena_for_type!([$($attrs),*]$args)
74     };
75 }
76
77 macro_rules! declare_arena {
78     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
79         #[derive(Default)]
80         pub struct Arena<$tcx> {
81             dropless: DroplessArena,
82             drop: DropArena,
83             $($name: arena_for_type!($a[$ty]),)*
84         }
85     }
86 }
87
88 macro_rules! which_arena_for_type {
89     ([][$arena:expr]) => {
90         Some($arena)
91     };
92     ([few$(, $attrs:ident)*][$arena:expr]) => {
93         None
94     };
95     ([$ignore:ident$(, $attrs:ident)*]$args:tt) => {
96         which_arena_for_type!([$($attrs),*]$args)
97     };
98 }
99
100 macro_rules! impl_arena_allocatable {
101     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
102         $(
103             impl ArenaAllocatable for $ty {}
104             unsafe impl<$tcx> ArenaField<$tcx> for $ty {
105                 #[inline]
106                 fn arena<'a>(_arena: &'a Arena<$tcx>) -> Option<&'a TypedArena<Self>> {
107                     which_arena_for_type!($a[&_arena.$name])
108                 }
109             }
110         )*
111     }
112 }
113
114 arena_types!(declare_arena, [], 'tcx);
115
116 arena_types!(impl_arena_allocatable, [], 'tcx);
117
118 pub trait ArenaAllocatable {}
119
120 impl<T: Copy> ArenaAllocatable for T {}
121
122 pub unsafe trait ArenaField<'tcx>: Sized {
123     /// Returns a specific arena to allocate from.
124     /// If None is returned, the DropArena will be used.
125     fn arena<'a>(arena: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>>;
126 }
127
128 unsafe impl<'tcx, T> ArenaField<'tcx> for T {
129     #[inline]
130     default fn arena<'a>(_: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>> {
131         panic!()
132     }
133 }
134
135 impl<'tcx> Arena<'tcx> {
136     #[inline]
137     pub fn alloc<T: ArenaAllocatable>(&self, value: T) -> &mut T {
138         if !mem::needs_drop::<T>() {
139             return self.dropless.alloc(value);
140         }
141         match <T as ArenaField<'tcx>>::arena(self) {
142             Some(arena) => arena.alloc(value),
143             None => unsafe { self.drop.alloc(value) },
144         }
145     }
146
147     #[inline]
148     pub fn alloc_slice<T: Copy>(&self, value: &[T]) -> &mut [T] {
149         if value.len() == 0 {
150             return &mut []
151         }
152         self.dropless.alloc_slice(value)
153     }
154
155     pub fn alloc_from_iter<
156         T: ArenaAllocatable,
157         I: IntoIterator<Item = T>
158     >(
159         &'a self,
160         iter: I
161     ) -> &'a mut [T] {
162         if !mem::needs_drop::<T>() {
163             return self.dropless.alloc_from_iter(iter);
164         }
165         match <T as ArenaField<'tcx>>::arena(self) {
166             Some(arena) => arena.alloc_from_iter(iter),
167             None => unsafe { self.drop.alloc_from_iter(iter) },
168         }
169     }
170 }
171
172 /// Calls the destructor for an object when dropped.
173 struct DropType {
174     drop_fn: unsafe fn(*mut u8),
175     obj: *mut u8,
176 }
177
178 unsafe fn drop_for_type<T>(to_drop: *mut u8) {
179     std::ptr::drop_in_place(to_drop as *mut T)
180 }
181
182 impl Drop for DropType {
183     fn drop(&mut self) {
184         unsafe {
185             (self.drop_fn)(self.obj)
186         }
187     }
188 }
189
190 /// An arena which can be used to allocate any type.
191 /// Allocating in this arena is unsafe since the type system
192 /// doesn't know which types it contains. In order to
193 /// allocate safely, you must store a PhantomData<T>
194 /// alongside this arena for each type T you allocate.
195 #[derive(Default)]
196 struct DropArena {
197     /// A list of destructors to run when the arena drops.
198     /// Ordered so `destructors` gets dropped before the arena
199     /// since its destructor can reference memory in the arena.
200     destructors: RefCell<Vec<DropType>>,
201     arena: DroplessArena,
202 }
203
204 impl DropArena {
205     #[inline]
206     unsafe fn alloc<T>(&self, object: T) -> &mut T {
207         let mem = self.arena.alloc_raw(
208             mem::size_of::<T>(),
209             mem::align_of::<T>()
210         ) as *mut _ as *mut T;
211         // Write into uninitialized memory.
212         ptr::write(mem, object);
213         let result = &mut *mem;
214         // Record the destructor after doing the allocation as that may panic
215         // and would cause `object`'s destuctor to run twice if it was recorded before
216         self.destructors.borrow_mut().push(DropType {
217             drop_fn: drop_for_type::<T>,
218             obj: result as *mut T as *mut u8,
219         });
220         result
221     }
222
223     #[inline]
224     unsafe fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
225         let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
226         if vec.is_empty() {
227             return &mut [];
228         }
229         let len = vec.len();
230
231         let start_ptr = self.arena.alloc_raw(
232             len.checked_mul(mem::size_of::<T>()).unwrap(),
233             mem::align_of::<T>()
234         ) as *mut _ as *mut T;
235
236         let mut destructors = self.destructors.borrow_mut();
237         // Reserve space for the destructors so we can't panic while adding them
238         destructors.reserve(len);
239
240         // Move the content to the arena by copying it and then forgetting
241         // the content of the SmallVec
242         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
243         mem::forget(vec.drain());
244
245         // Record the destructors after doing the allocation as that may panic
246         // and would cause `object`'s destuctor to run twice if it was recorded before
247         for i in 0..len {
248             destructors.push(DropType {
249                 drop_fn: drop_for_type::<T>,
250                 obj: start_ptr.offset(i as isize) as *mut u8,
251             });
252         }
253
254         slice::from_raw_parts_mut(start_ptr, len)
255     }
256 }