1 use arena::{TypedArena, DroplessArena};
5 use std::cell::RefCell;
6 use std::marker::PhantomData;
7 use smallvec::SmallVec;
9 /// This declares a list of types which can be allocated by `Arena`.
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.
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.
19 macro_rules! arena_types {
20 ($macro:path, $args:tt, $tcx:lifetime) => (
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::Body<$tcx>>,
27 [] mir: rustc::mir::Body<$tcx>,
28 [] steal_promoted: rustc::ty::steal::Steal<
29 rustc_data_structures::indexed_vec::IndexVec<
31 rustc::mir::Body<$tcx>
34 [] promoted: rustc_data_structures::indexed_vec::IndexVec<
36 rustc::mir::Body<$tcx>
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>
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_data_structures::bit_set::BitSet<rustc::mir::Local>,
49 [] trait_impls_of: rustc::ty::trait_def::TraitImpls,
51 rustc::infer::canonical::Canonical<'tcx,
52 rustc::infer::canonical::QueryResponse<'tcx,
53 rustc::traits::query::dropck_outlives::DropckOutlivesResult<'tcx>
56 [] normalize_projection_ty:
57 rustc::infer::canonical::Canonical<'tcx,
58 rustc::infer::canonical::QueryResponse<'tcx,
59 rustc::traits::query::normalize::NormalizationResult<'tcx>
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>>
69 rustc::infer::canonical::Canonical<'tcx,
70 rustc::infer::canonical::QueryResponse<'tcx, ()>
72 [] type_op_normalize_poly_fn_sig:
73 rustc::infer::canonical::Canonical<'tcx,
74 rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::PolyFnSig<'tcx>>
76 [] type_op_normalize_fn_sig:
77 rustc::infer::canonical::Canonical<'tcx,
78 rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::FnSig<'tcx>>
80 [] type_op_normalize_predicate:
81 rustc::infer::canonical::Canonical<'tcx,
82 rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Predicate<'tcx>>
84 [] type_op_normalize_ty:
85 rustc::infer::canonical::Canonical<'tcx,
86 rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Ty<'tcx>>
88 [few] crate_inherent_impls: rustc::ty::CrateInherentImpls,
89 [decode] borrowck: rustc::middle::borrowck::BorrowCheckResult,
90 [few] upstream_monomorphizations:
91 rustc::util::nodemap::DefIdMap<
92 rustc_data_structures::fx::FxHashMap<
93 rustc::ty::subst::SubstsRef<'tcx>,
94 rustc::hir::def_id::CrateNum
97 [few] resolve_lifetimes: rustc::middle::resolve_lifetime::ResolveLifetimes,
98 [decode] generic_predicates: rustc::ty::GenericPredicates<'tcx>,
99 [few] lint_levels: rustc::lint::LintLevelMap,
100 [few] stability_index: rustc::middle::stability::Index<'tcx>,
101 [few] features: syntax::feature_gate::Features,
102 [few] all_traits: Vec<rustc::hir::def_id::DefId>,
103 [few] privacy_access_levels: rustc::middle::privacy::AccessLevels,
104 [few] target_features_whitelist: rustc_data_structures::fx::FxHashMap<
106 Option<syntax::symbol::Symbol>
108 [few] wasm_import_module_map: rustc_data_structures::fx::FxHashMap<
109 rustc::hir::def_id::DefId,
112 [few] get_lib_features: rustc::middle::lib_features::LibFeatures,
113 [few] defined_lib_features: rustc::middle::lang_items::LanguageItems,
114 [few] visible_parent_map: rustc::util::nodemap::DefIdMap<rustc::hir::def_id::DefId>,
115 [few] foreign_module: rustc::middle::cstore::ForeignModule,
116 [few] foreign_modules: Vec<rustc::middle::cstore::ForeignModule>,
117 [few] reachable_non_generics: rustc::util::nodemap::DefIdMap<
118 rustc::middle::exported_symbols::SymbolExportLevel
120 [few] crate_variances: rustc::ty::CrateVariancesMap<'tcx>,
121 [few] inferred_outlives_crate: rustc::ty::CratePredicatesMap<'tcx>,
122 [] upvars: rustc_data_structures::fx::FxIndexMap<rustc::hir::HirId, rustc::hir::Upvar>,
127 macro_rules! arena_for_type {
131 ([few $(, $attrs:ident)*][$ty:ty]) => {
134 ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
135 arena_for_type!([$($attrs),*]$args)
139 macro_rules! declare_arena {
140 ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
142 pub struct Arena<$tcx> {
143 dropless: DroplessArena,
145 $($name: arena_for_type!($a[$ty]),)*
150 macro_rules! which_arena_for_type {
151 ([][$arena:expr]) => {
154 ([few$(, $attrs:ident)*][$arena:expr]) => {
157 ([$ignore:ident$(, $attrs:ident)*]$args:tt) => {
158 which_arena_for_type!([$($attrs),*]$args)
162 macro_rules! impl_arena_allocatable {
163 ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
165 impl ArenaAllocatable for $ty {}
166 unsafe impl<$tcx> ArenaField<$tcx> for $ty {
168 fn arena<'a>(_arena: &'a Arena<$tcx>) -> Option<&'a TypedArena<Self>> {
169 which_arena_for_type!($a[&_arena.$name])
176 arena_types!(declare_arena, [], 'tcx);
178 arena_types!(impl_arena_allocatable, [], 'tcx);
180 pub trait ArenaAllocatable {}
182 impl<T: Copy> ArenaAllocatable for T {}
184 unsafe trait ArenaField<'tcx>: Sized {
185 /// Returns a specific arena to allocate from.
186 /// If None is returned, the DropArena will be used.
187 fn arena<'a>(arena: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>>;
190 unsafe impl<'tcx, T> ArenaField<'tcx> for T {
192 default fn arena<'a>(_: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>> {
197 impl<'tcx> Arena<'tcx> {
199 pub fn alloc<T: ArenaAllocatable>(&self, value: T) -> &mut T {
200 if !mem::needs_drop::<T>() {
201 return self.dropless.alloc(value);
203 match <T as ArenaField<'tcx>>::arena(self) {
204 Some(arena) => arena.alloc(value),
205 None => unsafe { self.drop.alloc(value) },
210 pub fn alloc_slice<T: Copy>(&self, value: &[T]) -> &mut [T] {
211 if value.len() == 0 {
214 self.dropless.alloc_slice(value)
217 pub fn alloc_from_iter<
219 I: IntoIterator<Item = T>
224 if !mem::needs_drop::<T>() {
225 return self.dropless.alloc_from_iter(iter);
227 match <T as ArenaField<'tcx>>::arena(self) {
228 Some(arena) => arena.alloc_from_iter(iter),
229 None => unsafe { self.drop.alloc_from_iter(iter) },
234 /// Calls the destructor for an object when dropped.
236 drop_fn: unsafe fn(*mut u8),
240 unsafe fn drop_for_type<T>(to_drop: *mut u8) {
241 std::ptr::drop_in_place(to_drop as *mut T)
244 impl Drop for DropType {
247 (self.drop_fn)(self.obj)
252 /// An arena which can be used to allocate any type.
253 /// Allocating in this arena is unsafe since the type system
254 /// doesn't know which types it contains. In order to
255 /// allocate safely, you must store a PhantomData<T>
256 /// alongside this arena for each type T you allocate.
259 /// A list of destructors to run when the arena drops.
260 /// Ordered so `destructors` gets dropped before the arena
261 /// since its destructor can reference memory in the arena.
262 destructors: RefCell<Vec<DropType>>,
263 arena: DroplessArena,
268 unsafe fn alloc<T>(&self, object: T) -> &mut T {
269 let mem = self.arena.alloc_raw(
272 ) as *mut _ as *mut T;
273 // Write into uninitialized memory.
274 ptr::write(mem, object);
275 let result = &mut *mem;
276 // Record the destructor after doing the allocation as that may panic
277 // and would cause `object`'s destuctor to run twice if it was recorded before
278 self.destructors.borrow_mut().push(DropType {
279 drop_fn: drop_for_type::<T>,
280 obj: result as *mut T as *mut u8,
286 unsafe fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
287 let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
293 let start_ptr = self.arena.alloc_raw(
294 len.checked_mul(mem::size_of::<T>()).unwrap(),
296 ) as *mut _ as *mut T;
298 let mut destructors = self.destructors.borrow_mut();
299 // Reserve space for the destructors so we can't panic while adding them
300 destructors.reserve(len);
302 // Move the content to the arena by copying it and then forgetting
303 // the content of the SmallVec
304 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
305 mem::forget(vec.drain());
307 // Record the destructors after doing the allocation as that may panic
308 // and would cause `object`'s destuctor to run twice if it was recorded before
310 destructors.push(DropType {
311 drop_fn: drop_for_type::<T>,
312 obj: start_ptr.offset(i as isize) as *mut u8,
316 slice::from_raw_parts_mut(start_ptr, len)