]> git.lizzy.rs Git - rust.git/blob - src/unsize.rs
Rustup to rustc 1.37.0-nightly (2887008e0 2019-06-12)
[rust.git] / src / unsize.rs
1 use crate::prelude::*;
2
3 // Adapted from https://github.com/rust-lang/rust/blob/2a663555ddf36f6b041445894a8c175cd1bc718c/src/librustc_codegen_ssa/base.rs#L159-L307
4
5 /// Retrieve the information we are losing (making dynamic) in an unsizing
6 /// adjustment.
7 ///
8 /// The `old_info` argument is a bit funny. It is intended for use
9 /// in an upcast, where the new vtable for an object will be derived
10 /// from the old one.
11 pub fn unsized_info<'a, 'tcx: 'a>(
12     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
13     source: Ty<'tcx>,
14     target: Ty<'tcx>,
15     old_info: Option<Value>,
16 ) -> Value {
17     let (source, target) = fx.tcx.struct_lockstep_tails(source, target);
18     match (&source.sty, &target.sty) {
19         (&ty::Array(_, len), &ty::Slice(_)) => fx
20             .bcx
21             .ins()
22             .iconst(fx.pointer_type, len.unwrap_usize(fx.tcx) as i64),
23         (&ty::Dynamic(..), &ty::Dynamic(..)) => {
24             // For now, upcasts are limited to changes in marker
25             // traits, and hence never actually require an actual
26             // change to the vtable.
27             old_info.expect("unsized_info: missing old info for trait upcast")
28         }
29         (_, &ty::Dynamic(ref data, ..)) => crate::vtable::get_vtable(fx, source, data.principal()),
30         _ => bug!(
31             "unsized_info: invalid unsizing {:?} -> {:?}",
32             source,
33             target
34         ),
35     }
36 }
37
38 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
39 pub fn unsize_thin_ptr<'a, 'tcx: 'a>(
40     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
41     src: Value,
42     src_ty: Ty<'tcx>,
43     dst_ty: Ty<'tcx>,
44 ) -> (Value, Value) {
45     match (&src_ty.sty, &dst_ty.sty) {
46         (&ty::Ref(_, a, _), &ty::Ref(_, b, _))
47         | (&ty::Ref(_, a, _), &ty::RawPtr(ty::TypeAndMut { ty: b, .. }))
48         | (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
49             assert!(!fx.layout_of(a).is_unsized());
50             (src, unsized_info(fx, a, b, None))
51         }
52         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
53             let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
54             assert!(!fx.layout_of(a).is_unsized());
55             (src, unsized_info(fx, a, b, None))
56         }
57         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
58             assert_eq!(def_a, def_b);
59
60             let src_layout = fx.layout_of(src_ty);
61             let dst_layout = fx.layout_of(dst_ty);
62             let mut result = None;
63             for i in 0..src_layout.fields.count() {
64                 let src_f = src_layout.field(fx, i);
65                 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
66                 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
67                 if src_f.is_zst() {
68                     continue;
69                 }
70                 assert_eq!(src_layout.size, src_f.size);
71
72                 let dst_f = dst_layout.field(fx, i);
73                 assert_ne!(src_f.ty, dst_f.ty);
74                 assert_eq!(result, None);
75                 result = Some(unsize_thin_ptr(fx, src, src_f.ty, dst_f.ty));
76             }
77             result.unwrap()
78         }
79         _ => bug!("unsize_thin_ptr: called on bad types"),
80     }
81 }
82
83 /// Coerce `src`, which is a reference to a value of type `src_ty`,
84 /// to a value of type `dst_ty` and store the result in `dst`
85 pub fn coerce_unsized_into<'a, 'tcx: 'a>(
86     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
87     src: CValue<'tcx>,
88     dst: CPlace<'tcx>,
89 ) {
90     let src_ty = src.layout().ty;
91     let dst_ty = dst.layout().ty;
92     let mut coerce_ptr = || {
93         let (base, info) = if fx
94             .layout_of(src.layout().ty.builtin_deref(true).unwrap().ty)
95             .is_unsized()
96         {
97             // fat-ptr to fat-ptr unsize preserves the vtable
98             // i.e., &'a fmt::Debug+Send => &'a fmt::Debug
99             src.load_scalar_pair(fx)
100         } else {
101             let base = src.load_scalar(fx);
102             unsize_thin_ptr(fx, base, src_ty, dst_ty)
103         };
104         dst.write_cvalue(fx, CValue::by_val_pair(base, info, dst.layout()));
105     };
106     match (&src_ty.sty, &dst_ty.sty) {
107         (&ty::Ref(..), &ty::Ref(..))
108         | (&ty::Ref(..), &ty::RawPtr(..))
109         | (&ty::RawPtr(..), &ty::RawPtr(..)) => coerce_ptr(),
110         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
111             assert_eq!(def_a, def_b);
112
113             for i in 0..def_a.variants[VariantIdx::new(0)].fields.len() {
114                 let src_f = src.value_field(fx, mir::Field::new(i));
115                 let dst_f = dst.place_field(fx, mir::Field::new(i));
116
117                 if dst_f.layout().is_zst() {
118                     continue;
119                 }
120
121                 if src_f.layout().ty == dst_f.layout().ty {
122                     dst_f.write_cvalue(fx, src_f);
123                 } else {
124                     coerce_unsized_into(fx, src_f, dst_f);
125                 }
126             }
127         }
128         _ => bug!(
129             "coerce_unsized_into: invalid coercion {:?} -> {:?}",
130             src_ty,
131             dst_ty
132         ),
133     }
134 }
135
136 // Adapted from https://github.com/rust-lang/rust/blob/2a663555ddf36f6b041445894a8c175cd1bc718c/src/librustc_codegen_ssa/glue.rs
137
138 pub fn size_and_align_of_dst<'a, 'tcx: 'a>(
139     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
140     ty: Ty<'tcx>,
141     info: Value,
142 ) -> (Value, Value) {
143     let layout = fx.layout_of(ty);
144     if !layout.is_unsized() {
145         let size = fx
146             .bcx
147             .ins()
148             .iconst(fx.pointer_type, layout.size.bytes() as i64);
149         let align = fx
150             .bcx
151             .ins()
152             .iconst(fx.pointer_type, layout.align.abi.bytes() as i64);
153         return (size, align);
154     }
155     match ty.sty {
156         ty::Dynamic(..) => {
157             // load size/align from vtable
158             (
159                 crate::vtable::size_of_obj(fx, info),
160                 crate::vtable::min_align_of_obj(fx, info),
161             )
162         }
163         ty::Slice(_) | ty::Str => {
164             let unit = layout.field(fx, 0);
165             // The info in this case is the length of the str, so the size is that
166             // times the unit size.
167             (
168                 fx.bcx.ins().imul_imm(info, unit.size.bytes() as i64),
169                 fx.bcx
170                     .ins()
171                     .iconst(fx.pointer_type, unit.align.abi.bytes() as i64),
172             )
173         }
174         _ => {
175             // First get the size of all statically known fields.
176             // Don't use size_of because it also rounds up to alignment, which we
177             // want to avoid, as the unsized field's alignment could be smaller.
178             assert!(!ty.is_simd());
179
180             let i = layout.fields.count() - 1;
181             let sized_size = layout.fields.offset(i).bytes();
182             let sized_align = layout.align.abi.bytes();
183             let sized_align = fx.bcx.ins().iconst(fx.pointer_type, sized_align as i64);
184
185             // Recurse to get the size of the dynamically sized field (must be
186             // the last field).
187             let field_ty = layout.field(fx, i).ty;
188             let (unsized_size, mut unsized_align) = size_and_align_of_dst(fx, field_ty, info);
189
190             // FIXME (#26403, #27023): We should be adding padding
191             // to `sized_size` (to accommodate the `unsized_align`
192             // required of the unsized field that follows) before
193             // summing it with `sized_size`. (Note that since #26403
194             // is unfixed, we do not yet add the necessary padding
195             // here. But this is where the add would go.)
196
197             // Return the sum of sizes and max of aligns.
198             let size = fx.bcx.ins().iadd_imm(unsized_size, sized_size as i64);
199
200             // Packed types ignore the alignment of their fields.
201             if let ty::Adt(def, _) = ty.sty {
202                 if def.repr.packed() {
203                     unsized_align = sized_align;
204                 }
205             }
206
207             // Choose max of two known alignments (combined value must
208             // be aligned according to more restrictive of the two).
209             let cmp = fx
210                 .bcx
211                 .ins()
212                 .icmp(IntCC::UnsignedGreaterThan, sized_align, unsized_align);
213             let align = fx.bcx.ins().select(cmp, sized_align, unsized_align);
214
215             // Issue #27023: must add any necessary padding to `size`
216             // (to make it a multiple of `align`) before returning it.
217             //
218             // Namely, the returned size should be, in C notation:
219             //
220             //   `size + ((size & (align-1)) ? align : 0)`
221             //
222             // emulated via the semi-standard fast bit trick:
223             //
224             //   `(size + (align-1)) & -align`
225             let addend = fx.bcx.ins().iadd_imm(align, -1);
226             let add = fx.bcx.ins().iadd(size, addend);
227             let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
228             let neg = fx.bcx.ins().isub(zero, align);
229             let size = fx.bcx.ins().band(add, neg);
230
231             (size, align)
232         }
233     }
234 }