]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/glue.rs
translate drop glue using MIR
[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
17 use llvm;
18 use llvm::{ValueRef};
19 use rustc::traits;
20 use rustc::ty::{self, Ty, TypeFoldable};
21 use common::*;
22 use machine::*;
23 use meth;
24 use monomorphize;
25 use type_of::{sizing_type_of, align_of};
26 use value::Value;
27 use builder::Builder;
28
29 pub fn needs_drop_glue<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>, t: Ty<'tcx>) -> bool {
30     assert!(t.is_normalized_for_trans());
31
32     let t = scx.tcx().erase_regions(&t);
33
34     // FIXME (#22815): note that type_needs_drop conservatively
35     // approximates in some cases and may say a type expression
36     // requires drop glue when it actually does not.
37     //
38     // (In this case it is not clear whether any harm is done, i.e.
39     // erroneously returning `true` in some cases where we could have
40     // returned `false` does not appear unsound. The impact on
41     // code quality is unknown at this time.)
42
43     if !scx.type_needs_drop(t) {
44         return false;
45     }
46     match t.sty {
47         ty::TyAdt(def, _) if def.is_box() => {
48             let typ = t.boxed_ty();
49             if !scx.type_needs_drop(typ) && scx.type_is_sized(typ) {
50                 scx.tcx().infer_ctxt((), traits::Reveal::All).enter(|infcx| {
51                     let layout = t.layout(&infcx).unwrap();
52                     if layout.size(&scx.tcx().data_layout).bytes() == 0 {
53                         // `Box<ZeroSizeType>` does not allocate.
54                         false
55                     } else {
56                         true
57                     }
58                 })
59             } else {
60                 true
61             }
62         }
63         _ => true
64     }
65 }
66
67 pub fn size_and_align_of_dst<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, info: ValueRef)
68                                        -> (ValueRef, ValueRef) {
69     debug!("calculate size of DST: {}; with lost info: {:?}",
70            t, Value(info));
71     if bcx.ccx.shared().type_is_sized(t) {
72         let sizing_type = sizing_type_of(bcx.ccx, t);
73         let size = llsize_of_alloc(bcx.ccx, sizing_type);
74         let align = align_of(bcx.ccx, t);
75         debug!("size_and_align_of_dst t={} info={:?} size: {} align: {}",
76                t, Value(info), size, align);
77         let size = C_uint(bcx.ccx, size);
78         let align = C_uint(bcx.ccx, align);
79         return (size, align);
80     }
81     match t.sty {
82         ty::TyAdt(def, substs) => {
83             let ccx = bcx.ccx;
84             // First get the size of all statically known fields.
85             // Don't use type_of::sizing_type_of because that expects t to be sized,
86             // and it also rounds up to alignment, which we want to avoid,
87             // as the unsized field's alignment could be smaller.
88             assert!(!t.is_simd());
89             let layout = ccx.layout_of(t);
90             debug!("DST {} layout: {:?}", t, layout);
91
92             let (sized_size, sized_align) = match *layout {
93                 ty::layout::Layout::Univariant { ref variant, .. } => {
94                     (variant.offsets.last().map_or(0, |o| o.bytes()), variant.align.abi())
95                 }
96                 _ => {
97                     bug!("size_and_align_of_dst: expcted Univariant for `{}`, found {:#?}",
98                          t, layout);
99                 }
100             };
101             debug!("DST {} statically sized prefix size: {} align: {}",
102                    t, sized_size, sized_align);
103             let sized_size = C_uint(ccx, sized_size);
104             let sized_align = C_uint(ccx, sized_align);
105
106             // Recurse to get the size of the dynamically sized field (must be
107             // the last field).
108             let last_field = def.struct_variant().fields.last().unwrap();
109             let field_ty = monomorphize::field_ty(bcx.tcx(), substs, last_field);
110             let (unsized_size, unsized_align) = size_and_align_of_dst(bcx, field_ty, info);
111
112             // FIXME (#26403, #27023): We should be adding padding
113             // to `sized_size` (to accommodate the `unsized_align`
114             // required of the unsized field that follows) before
115             // summing it with `sized_size`. (Note that since #26403
116             // is unfixed, we do not yet add the necessary padding
117             // here. But this is where the add would go.)
118
119             // Return the sum of sizes and max of aligns.
120             let size = bcx.add(sized_size, unsized_size);
121
122             // Choose max of two known alignments (combined value must
123             // be aligned according to more restrictive of the two).
124             let align = match (const_to_opt_u128(sized_align, false),
125                                const_to_opt_u128(unsized_align, false)) {
126                 (Some(sized_align), Some(unsized_align)) => {
127                     // If both alignments are constant, (the sized_align should always be), then
128                     // pick the correct alignment statically.
129                     C_uint(ccx, std::cmp::max(sized_align, unsized_align) as u64)
130                 }
131                 _ => bcx.select(bcx.icmp(llvm::IntUGT, sized_align, unsized_align),
132                                 sized_align,
133                                 unsized_align)
134             };
135
136             // Issue #27023: must add any necessary padding to `size`
137             // (to make it a multiple of `align`) before returning it.
138             //
139             // Namely, the returned size should be, in C notation:
140             //
141             //   `size + ((size & (align-1)) ? align : 0)`
142             //
143             // emulated via the semi-standard fast bit trick:
144             //
145             //   `(size + (align-1)) & -align`
146
147             let addend = bcx.sub(align, C_uint(bcx.ccx, 1_u64));
148             let size = bcx.and(bcx.add(size, addend), bcx.neg(align));
149
150             (size, align)
151         }
152         ty::TyDynamic(..) => {
153             // load size/align from vtable
154             (meth::SIZE.get_usize(bcx, info), meth::ALIGN.get_usize(bcx, info))
155         }
156         ty::TySlice(_) | ty::TyStr => {
157             let unit_ty = t.sequence_element_type(bcx.tcx());
158             // The info in this case is the length of the str, so the size is that
159             // times the unit size.
160             let llunit_ty = sizing_type_of(bcx.ccx, unit_ty);
161             let unit_align = llalign_of_min(bcx.ccx, llunit_ty);
162             let unit_size = llsize_of_alloc(bcx.ccx, llunit_ty);
163             (bcx.mul(info, C_uint(bcx.ccx, unit_size)),
164              C_uint(bcx.ccx, unit_align))
165         }
166         _ => bug!("Unexpected unsized type, found {}", t)
167     }
168 }