]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/glue.rs
refactor away callee::Callee and translate virtual calls through a MIR shim
[rust.git] / src / librustc_trans / glue.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //!
12 //
13 // Code relating to drop glue.
14
15 use std;
16 use std::iter;
17
18 use llvm;
19 use llvm::{ValueRef, get_param};
20 use middle::lang_items::BoxFreeFnLangItem;
21 use rustc::ty::subst::{Substs};
22 use rustc::traits;
23 use rustc::ty::{self, layout, AdtDef, AdtKind, Ty, TypeFoldable};
24 use rustc::ty::subst::Kind;
25 use rustc::mir::tcx::LvalueTy;
26 use mir::lvalue::LvalueRef;
27 use abi::FnType;
28 use adt;
29 use base::*;
30 use callee::get_fn;
31 use cleanup::CleanupScope;
32 use common::*;
33 use machine::*;
34 use monomorphize;
35 use trans_item::TransItem;
36 use tvec;
37 use type_of::{type_of, sizing_type_of, align_of};
38 use type_::Type;
39 use value::Value;
40 use Disr;
41 use builder::Builder;
42
43 use mir::lvalue::Alignment;
44
45 pub fn trans_exchange_free_ty<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, ptr: LvalueRef<'tcx>) {
46     let content_ty = ptr.ty.to_ty(bcx.tcx());
47     let def_id = langcall(bcx.tcx(), None, "", BoxFreeFnLangItem);
48     let substs = bcx.tcx().mk_substs(iter::once(Kind::from(content_ty)));
49     let instance = monomorphize::resolve(bcx.ccx.shared(), def_id, substs);
50
51     let fn_ty = FnType::from_instance(bcx.ccx, &instance, &[]);
52     let llret = bcx.call(get_fn(bcx.ccx, instance),
53         &[ptr.llval, ptr.llextra][..1 + ptr.has_extra() as usize], None);
54     fn_ty.apply_attrs_callsite(llret);
55 }
56
57 pub fn get_drop_glue_type<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Ty<'tcx> {
58     assert!(t.is_normalized_for_trans());
59
60     let t = scx.tcx().erase_regions(&t);
61
62     // Even if there is no dtor for t, there might be one deeper down and we
63     // might need to pass in the vtable ptr.
64     if !scx.type_is_sized(t) {
65         return t;
66     }
67
68     // FIXME (#22815): note that type_needs_drop conservatively
69     // approximates in some cases and may say a type expression
70     // requires drop glue when it actually does not.
71     //
72     // (In this case it is not clear whether any harm is done, i.e.
73     // erroneously returning `t` in some cases where we could have
74     // returned `tcx.types.i8` does not appear unsound. The impact on
75     // code quality is unknown at this time.)
76
77     if !scx.type_needs_drop(t) {
78         return scx.tcx().types.i8;
79     }
80     match t.sty {
81         ty::TyAdt(def, _) if def.is_box() => {
82             let typ = t.boxed_ty();
83             if !scx.type_needs_drop(typ) && scx.type_is_sized(typ) {
84                 scx.tcx().infer_ctxt((), traits::Reveal::All).enter(|infcx| {
85                     let layout = t.layout(&infcx).unwrap();
86                     if layout.size(&scx.tcx().data_layout).bytes() == 0 {
87                         // `Box<ZeroSizeType>` does not allocate.
88                         scx.tcx().types.i8
89                     } else {
90                         t
91                     }
92                 })
93             } else {
94                 t
95             }
96         }
97         _ => t
98     }
99 }
100
101 fn drop_ty<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, args: LvalueRef<'tcx>) {
102     call_drop_glue(bcx, args, false, None)
103 }
104
105 pub fn call_drop_glue<'a, 'tcx>(
106     bcx: &Builder<'a, 'tcx>,
107     mut args: LvalueRef<'tcx>,
108     skip_dtor: bool,
109     funclet: Option<&'a Funclet>,
110 ) {
111     let t = args.ty.to_ty(bcx.tcx());
112     // NB: v is an *alias* of type t here, not a direct value.
113     debug!("call_drop_glue(t={:?}, skip_dtor={})", t, skip_dtor);
114     if bcx.ccx.shared().type_needs_drop(t) {
115         let ccx = bcx.ccx;
116         let g = if skip_dtor {
117             DropGlueKind::TyContents(t)
118         } else {
119             DropGlueKind::Ty(t)
120         };
121         let glue = get_drop_glue_core(ccx, g);
122         let glue_type = get_drop_glue_type(ccx.shared(), t);
123         if glue_type != t {
124             args.llval = bcx.pointercast(args.llval, type_of(ccx, glue_type).ptr_to());
125         }
126
127         // No drop-hint ==> call standard drop glue
128         bcx.call(glue, &[args.llval, args.llextra][..1 + args.has_extra() as usize],
129             funclet.map(|b| b.bundle()));
130     }
131 }
132
133 pub fn get_drop_glue<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> ValueRef {
134     get_drop_glue_core(ccx, DropGlueKind::Ty(t))
135 }
136
137 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
138 pub enum DropGlueKind<'tcx> {
139     /// The normal path; runs the dtor, and then recurs on the contents
140     Ty(Ty<'tcx>),
141     /// Skips the dtor, if any, for ty; drops the contents directly.
142     /// Note that the dtor is only skipped at the most *shallow*
143     /// level, namely, an `impl Drop for Ty` itself. So, for example,
144     /// if Ty is Newtype(S) then only the Drop impl for Newtype itself
145     /// will be skipped, while the Drop impl for S, if any, will be
146     /// invoked.
147     TyContents(Ty<'tcx>),
148 }
149
150 impl<'tcx> DropGlueKind<'tcx> {
151     pub fn ty(&self) -> Ty<'tcx> {
152         match *self { DropGlueKind::Ty(t) | DropGlueKind::TyContents(t) => t }
153     }
154
155     pub fn map_ty<F>(&self, mut f: F) -> DropGlueKind<'tcx> where F: FnMut(Ty<'tcx>) -> Ty<'tcx>
156     {
157         match *self {
158             DropGlueKind::Ty(t) => DropGlueKind::Ty(f(t)),
159             DropGlueKind::TyContents(t) => DropGlueKind::TyContents(f(t)),
160         }
161     }
162 }
163
164 fn get_drop_glue_core<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, g: DropGlueKind<'tcx>) -> ValueRef {
165     let g = g.map_ty(|t| get_drop_glue_type(ccx.shared(), t));
166     match ccx.drop_glues().borrow().get(&g) {
167         Some(&(glue, _)) => glue,
168         None => {
169             bug!("Could not find drop glue for {:?} -- {} -- {}.",
170                     g,
171                     TransItem::DropGlue(g).to_raw_string(),
172                     ccx.codegen_unit().name());
173         }
174     }
175 }
176
177 pub fn implement_drop_glue<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, g: DropGlueKind<'tcx>) {
178     assert_eq!(g.ty(), get_drop_glue_type(ccx.shared(), g.ty()));
179     let (llfn, _) = ccx.drop_glues().borrow().get(&g).unwrap().clone();
180
181     let mut bcx = Builder::new_block(ccx, llfn, "entry-block");
182
183     ccx.stats().n_glues_created.set(ccx.stats().n_glues_created.get() + 1);
184     // All glue functions take values passed *by alias*; this is a
185     // requirement since in many contexts glue is invoked indirectly and
186     // the caller has no idea if it's dealing with something that can be
187     // passed by value.
188     //
189     // llfn is expected be declared to take a parameter of the appropriate
190     // type, so we don't need to explicitly cast the function parameter.
191
192     // NB: v0 is an *alias* of type t here, not a direct value.
193     // Only drop the value when it ... well, we used to check for
194     // non-null, (and maybe we need to continue doing so), but we now
195     // must definitely check for special bit-patterns corresponding to
196     // the special dtor markings.
197     let t = g.ty();
198
199     let value = get_param(llfn, 0);
200     let ptr = if ccx.shared().type_is_sized(t) {
201         LvalueRef::new_sized_ty(value, t, Alignment::AbiAligned)
202     } else {
203         LvalueRef::new_unsized_ty(value, get_param(llfn, 1), t, Alignment::AbiAligned)
204     };
205
206     let skip_dtor = match g {
207         DropGlueKind::Ty(_) => false,
208         DropGlueKind::TyContents(_) => true
209     };
210
211     let bcx = match t.sty {
212         ty::TyAdt(def, _) if def.is_box() => {
213             // Support for Box is built-in as yet and its drop glue is special
214             // despite having a dummy Drop impl in the library.
215             assert!(!skip_dtor);
216             let content_ty = t.boxed_ty();
217             let ptr = if !bcx.ccx.shared().type_is_sized(content_ty) {
218                 let llbox = bcx.load(get_dataptr(&bcx, ptr.llval), None);
219                 let info = bcx.load(get_meta(&bcx, ptr.llval), None);
220                 LvalueRef::new_unsized_ty(llbox, info, content_ty, Alignment::AbiAligned)
221             } else {
222                 LvalueRef::new_sized_ty(
223                     bcx.load(ptr.llval, None),
224                     content_ty, Alignment::AbiAligned)
225             };
226             drop_ty(&bcx, ptr);
227             trans_exchange_free_ty(&bcx, ptr);
228             bcx
229         }
230         ty::TyDynamic(..) => {
231             // No support in vtable for distinguishing destroying with
232             // versus without calling Drop::drop. Assert caller is
233             // okay with always calling the Drop impl, if any.
234             assert!(!skip_dtor);
235             let dtor = bcx.load(ptr.llextra, None);
236             bcx.call(dtor, &[ptr.llval], None);
237             bcx
238         }
239         ty::TyAdt(def, ..) if def.has_dtor(bcx.tcx()) && !skip_dtor => {
240             let shallow_drop = def.is_union();
241             let tcx = bcx.tcx();
242
243             // Be sure to put the contents into a scope so we can use an invoke
244             // instruction to call the user destructor but still call the field
245             // destructors if the user destructor panics.
246             //
247             // FIXME (#14875) panic-in-drop semantics might be unsupported; we
248             // might well consider changing below to more direct code.
249             // Issue #23611: schedule cleanup of contents, re-inspecting the
250             // discriminant (if any) in case of variant swap in drop code.
251             let contents_scope = if !shallow_drop {
252                 CleanupScope::schedule_drop_adt_contents(&bcx, ptr)
253             } else {
254                 CleanupScope::noop()
255             };
256             let drop_trait_def_id = tcx.lang_items.drop_trait().unwrap();
257             let drop_method = tcx.associated_items(drop_trait_def_id)
258                 .find(|it| it.kind == ty::AssociatedKind::Method)
259                 .unwrap().def_id;
260             let self_type_substs = tcx.mk_substs_trait(t, &[]);
261             let drop_instance = monomorphize::resolve(
262                 bcx.ccx.shared(), drop_method, self_type_substs);
263             let fn_ty = FnType::from_instance(bcx.ccx, &drop_instance, &[]);
264             let llfn = get_fn(bcx.ccx, drop_instance);
265             let llret;
266             let args = &[ptr.llval, ptr.llextra][..1 + ptr.has_extra() as usize];
267             if let Some(landing_pad) = contents_scope.landing_pad {
268                 let normal_bcx = bcx.build_sibling_block("normal-return");
269                 llret = bcx.invoke(llfn, args, normal_bcx.llbb(), landing_pad, None);
270                 bcx = normal_bcx;
271             } else {
272                 llret = bcx.call(llfn, args, None);
273             }
274             fn_ty.apply_attrs_callsite(llret);
275             contents_scope.trans(&bcx);
276             bcx
277         }
278         ty::TyAdt(def, ..) if def.is_union() => {
279             bcx
280         }
281         _ => {
282             if bcx.ccx.shared().type_needs_drop(t) {
283                 drop_structural_ty(bcx, ptr)
284             } else {
285                 bcx
286             }
287         }
288     };
289     bcx.ret_void();
290 }
291
292 pub fn size_and_align_of_dst<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, info: ValueRef)
293                                        -> (ValueRef, ValueRef) {
294     debug!("calculate size of DST: {}; with lost info: {:?}",
295            t, Value(info));
296     if bcx.ccx.shared().type_is_sized(t) {
297         let sizing_type = sizing_type_of(bcx.ccx, t);
298         let size = llsize_of_alloc(bcx.ccx, sizing_type);
299         let align = align_of(bcx.ccx, t);
300         debug!("size_and_align_of_dst t={} info={:?} size: {} align: {}",
301                t, Value(info), size, align);
302         let size = C_uint(bcx.ccx, size);
303         let align = C_uint(bcx.ccx, align);
304         return (size, align);
305     }
306     match t.sty {
307         ty::TyAdt(def, substs) => {
308             let ccx = bcx.ccx;
309             // First get the size of all statically known fields.
310             // Don't use type_of::sizing_type_of because that expects t to be sized,
311             // and it also rounds up to alignment, which we want to avoid,
312             // as the unsized field's alignment could be smaller.
313             assert!(!t.is_simd());
314             let layout = ccx.layout_of(t);
315             debug!("DST {} layout: {:?}", t, layout);
316
317             let (sized_size, sized_align) = match *layout {
318                 ty::layout::Layout::Univariant { ref variant, .. } => {
319                     (variant.offsets.last().map_or(0, |o| o.bytes()), variant.align.abi())
320                 }
321                 _ => {
322                     bug!("size_and_align_of_dst: expcted Univariant for `{}`, found {:#?}",
323                          t, layout);
324                 }
325             };
326             debug!("DST {} statically sized prefix size: {} align: {}",
327                    t, sized_size, sized_align);
328             let sized_size = C_uint(ccx, sized_size);
329             let sized_align = C_uint(ccx, sized_align);
330
331             // Recurse to get the size of the dynamically sized field (must be
332             // the last field).
333             let last_field = def.struct_variant().fields.last().unwrap();
334             let field_ty = monomorphize::field_ty(bcx.tcx(), substs, last_field);
335             let (unsized_size, unsized_align) = size_and_align_of_dst(bcx, field_ty, info);
336
337             // FIXME (#26403, #27023): We should be adding padding
338             // to `sized_size` (to accommodate the `unsized_align`
339             // required of the unsized field that follows) before
340             // summing it with `sized_size`. (Note that since #26403
341             // is unfixed, we do not yet add the necessary padding
342             // here. But this is where the add would go.)
343
344             // Return the sum of sizes and max of aligns.
345             let size = bcx.add(sized_size, unsized_size);
346
347             // Choose max of two known alignments (combined value must
348             // be aligned according to more restrictive of the two).
349             let align = match (const_to_opt_u128(sized_align, false),
350                                const_to_opt_u128(unsized_align, false)) {
351                 (Some(sized_align), Some(unsized_align)) => {
352                     // If both alignments are constant, (the sized_align should always be), then
353                     // pick the correct alignment statically.
354                     C_uint(ccx, std::cmp::max(sized_align, unsized_align) as u64)
355                 }
356                 _ => bcx.select(bcx.icmp(llvm::IntUGT, sized_align, unsized_align),
357                                 sized_align,
358                                 unsized_align)
359             };
360
361             // Issue #27023: must add any necessary padding to `size`
362             // (to make it a multiple of `align`) before returning it.
363             //
364             // Namely, the returned size should be, in C notation:
365             //
366             //   `size + ((size & (align-1)) ? align : 0)`
367             //
368             // emulated via the semi-standard fast bit trick:
369             //
370             //   `(size + (align-1)) & -align`
371
372             let addend = bcx.sub(align, C_uint(bcx.ccx, 1_u64));
373             let size = bcx.and(bcx.add(size, addend), bcx.neg(align));
374
375             (size, align)
376         }
377         ty::TyDynamic(..) => {
378             // info points to the vtable and the second entry in the vtable is the
379             // dynamic size of the object.
380             let info = bcx.pointercast(info, Type::int(bcx.ccx).ptr_to());
381             let size_ptr = bcx.gepi(info, &[1]);
382             let align_ptr = bcx.gepi(info, &[2]);
383
384             let size = bcx.load(size_ptr, None);
385             let align = bcx.load(align_ptr, None);
386
387             // Vtable loads are invariant
388             bcx.set_invariant_load(size);
389             bcx.set_invariant_load(align);
390
391             (size, align)
392         }
393         ty::TySlice(_) | ty::TyStr => {
394             let unit_ty = t.sequence_element_type(bcx.tcx());
395             // The info in this case is the length of the str, so the size is that
396             // times the unit size.
397             let llunit_ty = sizing_type_of(bcx.ccx, unit_ty);
398             let unit_align = llalign_of_min(bcx.ccx, llunit_ty);
399             let unit_size = llsize_of_alloc(bcx.ccx, llunit_ty);
400             (bcx.mul(info, C_uint(bcx.ccx, unit_size)),
401              C_uint(bcx.ccx, unit_align))
402         }
403         _ => bug!("Unexpected unsized type, found {}", t)
404     }
405 }
406
407 // Iterates through the elements of a structural type, dropping them.
408 fn drop_structural_ty<'a, 'tcx>(
409     cx: Builder<'a, 'tcx>,
410     mut ptr: LvalueRef<'tcx>
411 ) -> Builder<'a, 'tcx> {
412     fn iter_variant_fields<'a, 'tcx>(
413         cx: &'a Builder<'a, 'tcx>,
414         av: LvalueRef<'tcx>,
415         adt_def: &'tcx AdtDef,
416         variant_index: usize,
417         substs: &'tcx Substs<'tcx>
418     ) {
419         let variant = &adt_def.variants[variant_index];
420         let tcx = cx.tcx();
421         for (i, field) in variant.fields.iter().enumerate() {
422             let arg = monomorphize::field_ty(tcx, substs, field);
423             let (field_ptr, align) = av.trans_field_ptr(&cx, i);
424             drop_ty(&cx, LvalueRef::new_sized_ty(field_ptr, arg, align));
425         }
426     }
427
428     let mut cx = cx;
429     let t = ptr.ty.to_ty(cx.tcx());
430     match t.sty {
431         ty::TyClosure(def_id, substs) => {
432             for (i, upvar_ty) in substs.upvar_tys(def_id, cx.tcx()).enumerate() {
433                 let (llupvar, align) = ptr.trans_field_ptr(&cx, i);
434                 drop_ty(&cx, LvalueRef::new_sized_ty(llupvar, upvar_ty, align));
435             }
436         }
437         ty::TyArray(_, n) => {
438             let base = get_dataptr(&cx, ptr.llval);
439             let len = C_uint(cx.ccx, n);
440             let unit_ty = t.sequence_element_type(cx.tcx());
441             cx = tvec::slice_for_each(&cx, base, unit_ty, len,
442                 |bb, vv| drop_ty(bb, LvalueRef::new_sized_ty(vv, unit_ty, ptr.alignment)));
443         }
444         ty::TySlice(_) | ty::TyStr => {
445             let unit_ty = t.sequence_element_type(cx.tcx());
446             cx = tvec::slice_for_each(&cx, ptr.llval, unit_ty, ptr.llextra,
447                 |bb, vv| drop_ty(bb, LvalueRef::new_sized_ty(vv, unit_ty, ptr.alignment)));
448         }
449         ty::TyTuple(ref args, _) => {
450             for (i, arg) in args.iter().enumerate() {
451                 let (llfld_a, align) = ptr.trans_field_ptr(&cx, i);
452                 drop_ty(&cx, LvalueRef::new_sized_ty(llfld_a, *arg, align));
453             }
454         }
455         ty::TyAdt(adt, substs) => match adt.adt_kind() {
456             AdtKind::Struct => {
457                 for (i, field) in adt.variants[0].fields.iter().enumerate() {
458                     let field_ty = monomorphize::field_ty(cx.tcx(), substs, field);
459                     let (llval, align) = ptr.trans_field_ptr(&cx, i);
460                     let field_ptr = if cx.ccx.shared().type_is_sized(field_ty) {
461                         LvalueRef::new_sized_ty(llval, field_ty, align)
462                     } else {
463                         LvalueRef::new_unsized_ty(llval, ptr.llextra, field_ty, align)
464                     };
465                     drop_ty(&cx, field_ptr);
466                 }
467             }
468             AdtKind::Union => {
469                 bug!("Union in `glue::drop_structural_ty`");
470             }
471             AdtKind::Enum => {
472                 let n_variants = adt.variants.len();
473
474                 // NB: we must hit the discriminant first so that structural
475                 // comparison know not to proceed when the discriminants differ.
476
477                 // Obtain a representation of the discriminant sufficient to translate
478                 // destructuring; this may or may not involve the actual discriminant.
479                 let l = cx.ccx.layout_of(t);
480                 match *l {
481                     layout::Univariant { .. } |
482                     layout::UntaggedUnion { .. } => {
483                         if n_variants != 0 {
484                             assert!(n_variants == 1);
485                             ptr.ty = LvalueTy::Downcast {
486                                 adt_def: adt,
487                                 substs: substs,
488                                 variant_index: 0,
489                             };
490                             iter_variant_fields(&cx, ptr, &adt, 0, substs);
491                         }
492                     }
493                     layout::CEnum { .. } |
494                     layout::General { .. } |
495                     layout::RawNullablePointer { .. } |
496                     layout::StructWrappedNullablePointer { .. } => {
497                         let lldiscrim_a = adt::trans_get_discr(
498                             &cx, t, ptr.llval, ptr.alignment, None, false);
499
500                         // Create a fall-through basic block for the "else" case of
501                         // the switch instruction we're about to generate. Note that
502                         // we do **not** use an Unreachable instruction here, even
503                         // though most of the time this basic block will never be hit.
504                         //
505                         // When an enum is dropped it's contents are currently
506                         // overwritten to DTOR_DONE, which means the discriminant
507                         // could have changed value to something not within the actual
508                         // range of the discriminant. Currently this function is only
509                         // used for drop glue so in this case we just return quickly
510                         // from the outer function, and any other use case will only
511                         // call this for an already-valid enum in which case the `ret
512                         // void` will never be hit.
513                         let ret_void_cx = cx.build_sibling_block("enum-iter-ret-void");
514                         ret_void_cx.ret_void();
515                         let llswitch = cx.switch(lldiscrim_a, ret_void_cx.llbb(), n_variants);
516                         let next_cx = cx.build_sibling_block("enum-iter-next");
517
518                         for (i, discr) in adt.discriminants(cx.tcx()).enumerate() {
519                             let variant_cx_name = format!("enum-iter-variant-{}", i);
520                             let variant_cx = cx.build_sibling_block(&variant_cx_name);
521                             let case_val = adt::trans_case(&cx, t, Disr::from(discr));
522                             variant_cx.add_case(llswitch, case_val, variant_cx.llbb());
523                             ptr.ty = LvalueTy::Downcast {
524                                 adt_def: adt,
525                                 substs: substs,
526                                 variant_index: i,
527                             };
528                             iter_variant_fields(&variant_cx, ptr, &adt, i, substs);
529                             variant_cx.br(next_cx.llbb());
530                         }
531                         cx = next_cx;
532                     }
533                     _ => bug!("{} is not an enum.", t),
534                 }
535             }
536         },
537
538         _ => {
539             cx.sess().unimpl(&format!("type in drop_structural_ty: {}", t))
540         }
541     }
542     return cx;
543 }