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