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