]> git.lizzy.rs Git - rust.git/blob - src/librustc/arena.rs
3f0c0277f8ac6424c6088230bde280132e2bd4ca
[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 /// This declares a list of types which can be allocated by `Arena`.
10 ///
11 /// The `few` modifier will cause allocation to use the shared arena and recording the destructor.
12 /// This is faster and more memory efficient if there's only a few allocations of the type.
13 /// Leaving `few` out will cause the type to get its own dedicated `TypedArena` which is
14 /// faster and more memory efficient if there is lots of allocations.
15 ///
16 /// Specifying the `decode` modifier will add decode impls for &T and &[T] where T is the type
17 /// listed. These impls will appear in the implement_ty_decoder! macro.
18 #[macro_export]
19 macro_rules! arena_types {
20     ($macro:path, $args:tt, $tcx:lifetime) => (
21         $macro!($args, [
22             [] layouts: rustc::ty::layout::LayoutDetails,
23             [] generics: rustc::ty::Generics,
24             [] trait_def: rustc::ty::TraitDef,
25             [] adt_def: rustc::ty::AdtDef,
26             [] steal_mir: rustc::ty::steal::Steal<rustc::mir::BodyAndCache<$tcx>>,
27             [] mir: rustc::mir::BodyAndCache<$tcx>,
28             [] steal_promoted: rustc::ty::steal::Steal<
29                 rustc_index::vec::IndexVec<
30                     rustc::mir::Promoted,
31                     rustc::mir::BodyAndCache<$tcx>
32                 >
33             >,
34             [] promoted: rustc_index::vec::IndexVec<
35                 rustc::mir::Promoted,
36                 rustc::mir::BodyAndCache<$tcx>
37             >,
38             [] tables: rustc::ty::TypeckTables<$tcx>,
39             [] const_allocs: rustc::mir::interpret::Allocation,
40             [] vtable_method: Option<(
41                 rustc::hir::def_id::DefId,
42                 rustc::ty::subst::SubstsRef<$tcx>
43             )>,
44             [few, decode] mir_keys: rustc::util::nodemap::DefIdSet,
45             [decode] specialization_graph: rustc::traits::specialization_graph::Graph,
46             [] region_scope_tree: rustc::middle::region::ScopeTree,
47             [] item_local_set: rustc::util::nodemap::ItemLocalSet,
48             [decode] mir_const_qualif: rustc_index::bit_set::BitSet<rustc::mir::Local>,
49             [] trait_impls_of: rustc::ty::trait_def::TraitImpls,
50             [] dropck_outlives:
51                 rustc::infer::canonical::Canonical<'tcx,
52                     rustc::infer::canonical::QueryResponse<'tcx,
53                         rustc::traits::query::dropck_outlives::DropckOutlivesResult<'tcx>
54                     >
55                 >,
56             [] normalize_projection_ty:
57                 rustc::infer::canonical::Canonical<'tcx,
58                     rustc::infer::canonical::QueryResponse<'tcx,
59                         rustc::traits::query::normalize::NormalizationResult<'tcx>
60                     >
61                 >,
62             [] implied_outlives_bounds:
63                 rustc::infer::canonical::Canonical<'tcx,
64                     rustc::infer::canonical::QueryResponse<'tcx,
65                         Vec<rustc::traits::query::outlives_bounds::OutlivesBound<'tcx>>
66                     >
67                 >,
68             [] type_op_subtype:
69                 rustc::infer::canonical::Canonical<'tcx,
70                     rustc::infer::canonical::QueryResponse<'tcx, ()>
71                 >,
72             [] type_op_normalize_poly_fn_sig:
73                 rustc::infer::canonical::Canonical<'tcx,
74                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::PolyFnSig<'tcx>>
75                 >,
76             [] type_op_normalize_fn_sig:
77                 rustc::infer::canonical::Canonical<'tcx,
78                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::FnSig<'tcx>>
79                 >,
80             [] type_op_normalize_predicate:
81                 rustc::infer::canonical::Canonical<'tcx,
82                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Predicate<'tcx>>
83                 >,
84             [] type_op_normalize_ty:
85                 rustc::infer::canonical::Canonical<'tcx,
86                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Ty<'tcx>>
87                 >,
88             [few] crate_inherent_impls: rustc::ty::CrateInherentImpls,
89             [few] upstream_monomorphizations:
90                 rustc::util::nodemap::DefIdMap<
91                     rustc_data_structures::fx::FxHashMap<
92                         rustc::ty::subst::SubstsRef<'tcx>,
93                         rustc::hir::def_id::CrateNum
94                     >
95                 >,
96             [few] diagnostic_items: rustc_data_structures::fx::FxHashMap<
97                 syntax::symbol::Symbol,
98                 rustc::hir::def_id::DefId,
99             >,
100             [few] resolve_lifetimes: rustc::middle::resolve_lifetime::ResolveLifetimes,
101             [few] lint_levels: rustc::lint::LintLevelMap,
102             [few] stability_index: rustc::middle::stability::Index<'tcx>,
103             [few] features: rustc_feature::Features,
104             [few] all_traits: Vec<rustc::hir::def_id::DefId>,
105             [few] privacy_access_levels: rustc::middle::privacy::AccessLevels,
106             [few] target_features_whitelist: rustc_data_structures::fx::FxHashMap<
107                 String,
108                 Option<syntax::symbol::Symbol>
109             >,
110             [few] wasm_import_module_map: rustc_data_structures::fx::FxHashMap<
111                 rustc::hir::def_id::DefId,
112                 String
113             >,
114             [few] get_lib_features: rustc::middle::lib_features::LibFeatures,
115             [few] defined_lib_features: rustc::middle::lang_items::LanguageItems,
116             [few] visible_parent_map: rustc::util::nodemap::DefIdMap<rustc::hir::def_id::DefId>,
117             [few] foreign_module: rustc::middle::cstore::ForeignModule,
118             [few] foreign_modules: Vec<rustc::middle::cstore::ForeignModule>,
119             [few] reachable_non_generics: rustc::util::nodemap::DefIdMap<
120                 rustc::middle::exported_symbols::SymbolExportLevel
121             >,
122             [few] crate_variances: rustc::ty::CrateVariancesMap<'tcx>,
123             [few] inferred_outlives_crate: rustc::ty::CratePredicatesMap<'tcx>,
124             [] upvars: rustc_data_structures::fx::FxIndexMap<rustc::hir::HirId, rustc::hir::Upvar>,
125             // HIR nodes arenas
126             [few] hir_forest: rustc::hir::map::Forest<$tcx>,
127             [] attribute: syntax::ast::Attribute,
128             [] global_asm: rustc::hir::GlobalAsm,
129             [] fn_decl: rustc::hir::FnDecl,
130             [] foreign_item: rustc::hir::ForeignItem<$tcx>,
131             [] impl_item_ref: rustc::hir::ImplItemRef,
132             [] macro_def: rustc::hir::MacroDef<$tcx>,
133             [] path: rustc::hir::Path,
134             [] trait_item_ref: rustc::hir::TraitItemRef,
135             [] ty: rustc::hir::Ty,
136         ], $tcx);
137     )
138 }
139
140 macro_rules! arena_for_type {
141     ([][$ty:ty]) => {
142         TypedArena<$ty>
143     };
144     ([few $(, $attrs:ident)*][$ty:ty]) => {
145         PhantomData<$ty>
146     };
147     ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
148         arena_for_type!([$($attrs),*]$args)
149     };
150 }
151
152 macro_rules! declare_arena {
153     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
154         #[derive(Default)]
155         pub struct Arena<$tcx> {
156             dropless: DroplessArena,
157             drop: DropArena,
158             $($name: arena_for_type!($a[$ty]),)*
159         }
160     }
161 }
162
163 macro_rules! which_arena_for_type {
164     ([][$arena:expr]) => {
165         Some($arena)
166     };
167     ([few$(, $attrs:ident)*][$arena:expr]) => {
168         None
169     };
170     ([$ignore:ident$(, $attrs:ident)*]$args:tt) => {
171         which_arena_for_type!([$($attrs),*]$args)
172     };
173 }
174
175 macro_rules! impl_arena_allocatable {
176     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
177         $(
178             impl ArenaAllocatable for $ty {}
179             unsafe impl<$tcx> ArenaField<$tcx> for $ty {
180                 #[inline]
181                 fn arena<'a>(_arena: &'a Arena<$tcx>) -> Option<&'a TypedArena<Self>> {
182                     which_arena_for_type!($a[&_arena.$name])
183                 }
184             }
185         )*
186     }
187 }
188
189 arena_types!(declare_arena, [], 'tcx);
190
191 arena_types!(impl_arena_allocatable, [], 'tcx);
192
193 pub trait ArenaAllocatable {}
194
195 impl<T: Copy> ArenaAllocatable for T {}
196
197 unsafe trait ArenaField<'tcx>: Sized {
198     /// Returns a specific arena to allocate from.
199     /// If `None` is returned, the `DropArena` will be used.
200     fn arena<'a>(arena: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>>;
201 }
202
203 unsafe impl<'tcx, T> ArenaField<'tcx> for T {
204     #[inline]
205     default fn arena<'a>(_: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>> {
206         panic!()
207     }
208 }
209
210 impl<'tcx> Arena<'tcx> {
211     #[inline]
212     pub fn alloc<T: ArenaAllocatable>(&self, value: T) -> &mut T {
213         if !mem::needs_drop::<T>() {
214             return self.dropless.alloc(value);
215         }
216         match <T as ArenaField<'tcx>>::arena(self) {
217             Some(arena) => arena.alloc(value),
218             None => unsafe { self.drop.alloc(value) },
219         }
220     }
221
222     #[inline]
223     pub fn alloc_slice<T: Copy>(&self, value: &[T]) -> &mut [T] {
224         if value.len() == 0 {
225             return &mut []
226         }
227         self.dropless.alloc_slice(value)
228     }
229
230     pub fn alloc_from_iter<
231         T: ArenaAllocatable,
232         I: IntoIterator<Item = T>
233     >(
234         &'a self,
235         iter: I
236     ) -> &'a mut [T] {
237         if !mem::needs_drop::<T>() {
238             return self.dropless.alloc_from_iter(iter);
239         }
240         match <T as ArenaField<'tcx>>::arena(self) {
241             Some(arena) => arena.alloc_from_iter(iter),
242             None => unsafe { self.drop.alloc_from_iter(iter) },
243         }
244     }
245 }
246
247 /// Calls the destructor for an object when dropped.
248 struct DropType {
249     drop_fn: unsafe fn(*mut u8),
250     obj: *mut u8,
251 }
252
253 unsafe fn drop_for_type<T>(to_drop: *mut u8) {
254     std::ptr::drop_in_place(to_drop as *mut T)
255 }
256
257 impl Drop for DropType {
258     fn drop(&mut self) {
259         unsafe {
260             (self.drop_fn)(self.obj)
261         }
262     }
263 }
264
265 /// An arena which can be used to allocate any type.
266 /// Allocating in this arena is unsafe since the type system
267 /// doesn't know which types it contains. In order to
268 /// allocate safely, you must store a PhantomData<T>
269 /// alongside this arena for each type T you allocate.
270 #[derive(Default)]
271 struct DropArena {
272     /// A list of destructors to run when the arena drops.
273     /// Ordered so `destructors` gets dropped before the arena
274     /// since its destructor can reference memory in the arena.
275     destructors: RefCell<Vec<DropType>>,
276     arena: DroplessArena,
277 }
278
279 impl DropArena {
280     #[inline]
281     unsafe fn alloc<T>(&self, object: T) -> &mut T {
282         let mem = self.arena.alloc_raw(
283             mem::size_of::<T>(),
284             mem::align_of::<T>()
285         ) as *mut _ as *mut T;
286         // Write into uninitialized memory.
287         ptr::write(mem, object);
288         let result = &mut *mem;
289         // Record the destructor after doing the allocation as that may panic
290         // and would cause `object`'s destuctor to run twice if it was recorded before
291         self.destructors.borrow_mut().push(DropType {
292             drop_fn: drop_for_type::<T>,
293             obj: result as *mut T as *mut u8,
294         });
295         result
296     }
297
298     #[inline]
299     unsafe fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
300         let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
301         if vec.is_empty() {
302             return &mut [];
303         }
304         let len = vec.len();
305
306         let start_ptr = self.arena.alloc_raw(
307             len.checked_mul(mem::size_of::<T>()).unwrap(),
308             mem::align_of::<T>()
309         ) as *mut _ as *mut T;
310
311         let mut destructors = self.destructors.borrow_mut();
312         // Reserve space for the destructors so we can't panic while adding them
313         destructors.reserve(len);
314
315         // Move the content to the arena by copying it and then forgetting
316         // the content of the SmallVec
317         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
318         mem::forget(vec.drain(..));
319
320         // Record the destructors after doing the allocation as that may panic
321         // and would cause `object`'s destuctor to run twice if it was recorded before
322         for i in 0..len {
323             destructors.push(DropType {
324                 drop_fn: drop_for_type::<T>,
325                 obj: start_ptr.offset(i as isize) as *mut u8,
326             });
327         }
328
329         slice::from_raw_parts_mut(start_ptr, len)
330     }
331 }