1 use arena::{DroplessArena, TypedArena};
2 use smallvec::SmallVec;
3 use std::cell::RefCell;
4 use std::marker::PhantomData;
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::BodyAndCache<$tcx>>,
27 [] mir: rustc::mir::BodyAndCache<$tcx>,
28 [] steal_promoted: rustc::ty::steal::Steal<
29 rustc_index::vec::IndexVec<
31 rustc::mir::BodyAndCache<$tcx>
34 [] promoted: rustc_index::vec::IndexVec<
36 rustc::mir::BodyAndCache<$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_index::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 [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
96 [few] diagnostic_items: rustc_data_structures::fx::FxHashMap<
97 syntax::symbol::Symbol,
98 rustc::hir::def_id::DefId,
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<
108 Option<syntax::symbol::Symbol>
110 [few] wasm_import_module_map: rustc_data_structures::fx::FxHashMap<
111 rustc::hir::def_id::DefId,
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
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>,
127 [few] hir_forest: rustc::hir::map::Forest<$tcx>,
128 [] arm: rustc::hir::Arm<$tcx>,
129 [] attribute: syntax::ast::Attribute,
130 [] block: rustc::hir::Block<$tcx>,
131 [few] global_asm: rustc::hir::GlobalAsm,
132 [] expr: rustc::hir::Expr<$tcx>,
133 [] field: rustc::hir::Field<$tcx>,
134 [] field_pat: rustc::hir::FieldPat<$tcx>,
135 [] fn_decl: rustc::hir::FnDecl,
136 [] foreign_item: rustc::hir::ForeignItem<$tcx>,
137 [] impl_item_ref: rustc::hir::ImplItemRef,
138 [] inline_asm: rustc::hir::InlineAsm<$tcx>,
139 [] local: rustc::hir::Local<$tcx>,
140 [few] macro_def: rustc::hir::MacroDef<$tcx>,
141 [] param: rustc::hir::Param<$tcx>,
142 [] pat: rustc::hir::Pat<$tcx>,
143 [] path: rustc::hir::Path,
144 [] path_segment: rustc::hir::PathSegment,
145 [] qpath: rustc::hir::QPath,
146 [] stmt: rustc::hir::Stmt<$tcx>,
147 [] struct_field: rustc::hir::StructField<$tcx>,
148 [] trait_item_ref: rustc::hir::TraitItemRef,
149 [] ty: rustc::hir::Ty,
150 [] variant: rustc::hir::Variant<$tcx>,
155 macro_rules! arena_for_type {
159 ([few $(, $attrs:ident)*][$ty:ty]) => {
162 ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
163 arena_for_type!([$($attrs),*]$args)
167 macro_rules! declare_arena {
168 ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
170 pub struct Arena<$tcx> {
171 dropless: DroplessArena,
173 $($name: arena_for_type!($a[$ty]),)*
178 macro_rules! which_arena_for_type {
179 ([][$arena:expr]) => {
182 ([few$(, $attrs:ident)*][$arena:expr]) => {
185 ([$ignore:ident$(, $attrs:ident)*]$args:tt) => {
186 which_arena_for_type!([$($attrs),*]$args)
190 macro_rules! impl_arena_allocatable {
191 ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
193 impl ArenaAllocatable for $ty {}
194 unsafe impl<$tcx> ArenaField<$tcx> for $ty {
196 fn arena<'a>(_arena: &'a Arena<$tcx>) -> Option<&'a TypedArena<Self>> {
197 which_arena_for_type!($a[&_arena.$name])
204 arena_types!(declare_arena, [], 'tcx);
206 arena_types!(impl_arena_allocatable, [], 'tcx);
208 pub trait ArenaAllocatable {}
210 impl<T: Copy> ArenaAllocatable for T {}
212 unsafe trait ArenaField<'tcx>: Sized {
213 /// Returns a specific arena to allocate from.
214 /// If `None` is returned, the `DropArena` will be used.
215 fn arena<'a>(arena: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>>;
218 unsafe impl<'tcx, T> ArenaField<'tcx> for T {
220 default fn arena<'a>(_: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>> {
225 impl<'tcx> Arena<'tcx> {
227 pub fn alloc<T: ArenaAllocatable>(&self, value: T) -> &mut T {
228 if !mem::needs_drop::<T>() {
229 return self.dropless.alloc(value);
231 match <T as ArenaField<'tcx>>::arena(self) {
232 Some(arena) => arena.alloc(value),
233 None => unsafe { self.drop.alloc(value) },
238 pub fn alloc_slice<T: Copy>(&self, value: &[T]) -> &mut [T] {
239 if value.len() == 0 {
242 self.dropless.alloc_slice(value)
245 pub fn alloc_from_iter<T: ArenaAllocatable, I: IntoIterator<Item = T>>(
249 if !mem::needs_drop::<T>() {
250 return self.dropless.alloc_from_iter(iter);
252 match <T as ArenaField<'tcx>>::arena(self) {
253 Some(arena) => arena.alloc_from_iter(iter),
254 None => unsafe { self.drop.alloc_from_iter(iter) },
259 /// Calls the destructor for an object when dropped.
261 drop_fn: unsafe fn(*mut u8),
265 unsafe fn drop_for_type<T>(to_drop: *mut u8) {
266 std::ptr::drop_in_place(to_drop as *mut T)
269 impl Drop for DropType {
271 unsafe { (self.drop_fn)(self.obj) }
275 /// An arena which can be used to allocate any type.
276 /// Allocating in this arena is unsafe since the type system
277 /// doesn't know which types it contains. In order to
278 /// allocate safely, you must store a PhantomData<T>
279 /// alongside this arena for each type T you allocate.
282 /// A list of destructors to run when the arena drops.
283 /// Ordered so `destructors` gets dropped before the arena
284 /// since its destructor can reference memory in the arena.
285 destructors: RefCell<Vec<DropType>>,
286 arena: DroplessArena,
291 unsafe fn alloc<T>(&self, object: T) -> &mut T {
293 self.arena.alloc_raw(mem::size_of::<T>(), mem::align_of::<T>()) as *mut _ as *mut T;
294 // Write into uninitialized memory.
295 ptr::write(mem, object);
296 let result = &mut *mem;
297 // Record the destructor after doing the allocation as that may panic
298 // and would cause `object`'s destuctor to run twice if it was recorded before
301 .push(DropType { drop_fn: drop_for_type::<T>, obj: result as *mut T as *mut u8 });
306 unsafe fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
307 let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
315 .alloc_raw(len.checked_mul(mem::size_of::<T>()).unwrap(), mem::align_of::<T>())
318 let mut destructors = self.destructors.borrow_mut();
319 // Reserve space for the destructors so we can't panic while adding them
320 destructors.reserve(len);
322 // Move the content to the arena by copying it and then forgetting
323 // the content of the SmallVec
324 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
325 mem::forget(vec.drain(..));
327 // Record the destructors after doing the allocation as that may panic
328 // and would cause `object`'s destuctor to run twice if it was recorded before
330 destructors.push(DropType {
331 drop_fn: drop_for_type::<T>,
332 obj: start_ptr.offset(i as isize) as *mut u8,
336 slice::from_raw_parts_mut(start_ptr, len)