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