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