]> git.lizzy.rs Git - rust.git/blob - src/value_and_place.rs
Remove vector support from load_scalar
[rust.git] / src / value_and_place.rs
1 use crate::prelude::*;
2
3 use cranelift_codegen::ir::immediates::Offset32;
4
5 fn codegen_field<'tcx>(
6     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
7     base: Pointer,
8     extra: Option<Value>,
9     layout: TyLayout<'tcx>,
10     field: mir::Field,
11 ) -> (Pointer, TyLayout<'tcx>) {
12     let field_offset = layout.fields.offset(field.index());
13     let field_layout = layout.field(&*fx, field.index());
14
15     let simple = |fx: &mut FunctionCx<_>| {
16         (
17             base.offset_i64(fx, i64::try_from(field_offset.bytes()).unwrap()),
18             field_layout,
19         )
20     };
21
22     if let Some(extra) = extra {
23         if !field_layout.is_unsized() {
24             return simple(fx);
25         }
26         match field_layout.ty.kind {
27             ty::Slice(..) | ty::Str | ty::Foreign(..) => return simple(fx),
28             ty::Adt(def, _) if def.repr.packed() => {
29                 assert_eq!(layout.align.abi.bytes(), 1);
30                 return simple(fx);
31             }
32             _ => {
33                 // We have to align the offset for DST's
34                 let unaligned_offset = field_offset.bytes();
35                 let (_, unsized_align) = crate::unsize::size_and_align_of_dst(fx, field_layout.ty, extra);
36
37                 let one = fx.bcx.ins().iconst(pointer_ty(fx.tcx), 1);
38                 let align_sub_1 = fx.bcx.ins().isub(unsized_align, one);
39                 let and_lhs = fx.bcx.ins().iadd_imm(align_sub_1, unaligned_offset as i64);
40                 let zero = fx.bcx.ins().iconst(pointer_ty(fx.tcx), 0);
41                 let and_rhs = fx.bcx.ins().isub(zero, unsized_align);
42                 let offset = fx.bcx.ins().band(and_lhs, and_rhs);
43
44                 (
45                     base.offset_value(fx, offset),
46                     field_layout,
47                 )
48             }
49         }
50     } else {
51         simple(fx)
52     }
53 }
54
55 fn scalar_pair_calculate_b_offset(tcx: TyCtxt<'_>, a_scalar: &Scalar, b_scalar: &Scalar) -> Offset32 {
56     let b_offset = a_scalar
57         .value
58         .size(&tcx)
59         .align_to(b_scalar.value.align(&tcx).abi);
60     Offset32::new(b_offset.bytes().try_into().unwrap())
61 }
62
63 /// A read-only value
64 #[derive(Debug, Copy, Clone)]
65 pub struct CValue<'tcx>(CValueInner, TyLayout<'tcx>);
66
67 #[derive(Debug, Copy, Clone)]
68 enum CValueInner {
69     ByRef(Pointer),
70     ByVal(Value),
71     ByValPair(Value, Value),
72 }
73
74 impl<'tcx> CValue<'tcx> {
75     pub fn by_ref(ptr: Pointer, layout: TyLayout<'tcx>) -> CValue<'tcx> {
76         CValue(CValueInner::ByRef(ptr), layout)
77     }
78
79     pub fn by_val(value: Value, layout: TyLayout<'tcx>) -> CValue<'tcx> {
80         CValue(CValueInner::ByVal(value), layout)
81     }
82
83     pub fn by_val_pair(value: Value, extra: Value, layout: TyLayout<'tcx>) -> CValue<'tcx> {
84         CValue(CValueInner::ByValPair(value, extra), layout)
85     }
86
87     pub fn layout(&self) -> TyLayout<'tcx> {
88         self.1
89     }
90
91     pub fn force_stack<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Pointer {
92         let layout = self.1;
93         match self.0 {
94             CValueInner::ByRef(ptr) => ptr,
95             CValueInner::ByVal(_) | CValueInner::ByValPair(_, _) => {
96                 let cplace = CPlace::new_stack_slot(fx, layout.ty);
97                 cplace.write_cvalue(fx, self);
98                 cplace.to_ptr(fx)
99             }
100         }
101     }
102
103     pub fn try_to_addr(self) -> Option<Value> {
104         match self.0 {
105             CValueInner::ByRef(ptr) => {
106                 if let Some((base_addr, offset)) = ptr.try_get_addr_and_offset() {
107                     if offset == Offset32::new(0) {
108                         Some(base_addr)
109                     } else {
110                         None
111                     }
112                 } else {
113                     None
114                 }
115             }
116             CValueInner::ByVal(_) | CValueInner::ByValPair(_, _) => None,
117         }
118     }
119
120     /// Load a value with layout.abi of scalar
121     pub fn load_scalar<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Value {
122         let layout = self.1;
123         match self.0 {
124             CValueInner::ByRef(ptr) => {
125                 let scalar = match layout.abi {
126                     layout::Abi::Scalar(ref scalar) => scalar.clone(),
127                     _ => unreachable!(),
128                 };
129                 let clif_ty = scalar_to_clif_type(fx.tcx, scalar);
130                 ptr.load(fx, clif_ty, MemFlags::new())
131             }
132             CValueInner::ByVal(value) => value,
133             CValueInner::ByValPair(_, _) => bug!("Please use load_scalar_pair for ByValPair"),
134         }
135     }
136
137     /// Load a value pair with layout.abi of scalar pair
138     pub fn load_scalar_pair<'a>(
139         self,
140         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
141     ) -> (Value, Value) {
142         let layout = self.1;
143         match self.0 {
144             CValueInner::ByRef(ptr) => {
145                 let (a_scalar, b_scalar) = match &layout.abi {
146                     layout::Abi::ScalarPair(a, b) => (a, b),
147                     _ => unreachable!("load_scalar_pair({:?})", self),
148                 };
149                 let b_offset = scalar_pair_calculate_b_offset(fx.tcx, a_scalar, b_scalar);
150                 let clif_ty1 = scalar_to_clif_type(fx.tcx, a_scalar.clone());
151                 let clif_ty2 = scalar_to_clif_type(fx.tcx, b_scalar.clone());
152                 let val1 = ptr.load(fx, clif_ty1, MemFlags::new());
153                 let val2 = ptr.offset(fx, b_offset).load(fx, clif_ty2, MemFlags::new());
154                 (val1, val2)
155             }
156             CValueInner::ByVal(_) => bug!("Please use load_scalar for ByVal"),
157             CValueInner::ByValPair(val1, val2) => (val1, val2),
158         }
159     }
160
161     /// Load a value with layout.abi of vector
162     pub fn load_vector<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Value {
163         let layout = self.1;
164         match self.0 {
165             CValueInner::ByRef(ptr) => {
166                 let clif_ty = match layout.abi {
167                     layout::Abi::Vector { ref element, count } => {
168                         scalar_to_clif_type(fx.tcx, element.clone()).by(u16::try_from(count).unwrap()).unwrap()
169                     }
170                     _ => unreachable!(),
171                 };
172                 ptr.load(fx, clif_ty, MemFlags::new())
173             }
174             CValueInner::ByVal(value) => value,
175             CValueInner::ByValPair(_, _) => bug!("Please use load_scalar_pair for ByValPair"),
176         }
177     }
178
179     pub fn value_field<'a>(
180         self,
181         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
182         field: mir::Field,
183     ) -> CValue<'tcx> {
184         let layout = self.1;
185         let ptr = match self.0 {
186             CValueInner::ByRef(ptr) => ptr,
187             _ => bug!("place_field for {:?}", self),
188         };
189
190         let (field_ptr, field_layout) = codegen_field(fx, ptr, None, layout, field);
191         CValue::by_ref(field_ptr, field_layout)
192     }
193
194     pub fn unsize_value<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
195         crate::unsize::coerce_unsized_into(fx, self, dest);
196     }
197
198     /// If `ty` is signed, `const_val` must already be sign extended.
199     pub fn const_val<'a>(
200         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
201         ty: Ty<'tcx>,
202         const_val: u128,
203     ) -> CValue<'tcx> {
204         let clif_ty = fx.clif_type(ty).unwrap();
205         let layout = fx.layout_of(ty);
206
207         let val = match ty.kind {
208             ty::TyKind::Uint(UintTy::U128) | ty::TyKind::Int(IntTy::I128) => {
209                 let lsb = fx.bcx.ins().iconst(types::I64, const_val as u64 as i64);
210                 let msb = fx
211                     .bcx
212                     .ins()
213                     .iconst(types::I64, (const_val >> 64) as u64 as i64);
214                 fx.bcx.ins().iconcat(lsb, msb)
215             }
216             ty::TyKind::Bool => {
217                 assert!(
218                     const_val == 0 || const_val == 1,
219                     "Invalid bool 0x{:032X}",
220                     const_val
221                 );
222                 fx.bcx.ins().iconst(types::I8, const_val as i64)
223             }
224             ty::TyKind::Uint(_) | ty::TyKind::Ref(..) | ty::TyKind::RawPtr(..) => fx
225                 .bcx
226                 .ins()
227                 .iconst(clif_ty, u64::try_from(const_val).expect("uint") as i64),
228             ty::TyKind::Int(_) => fx.bcx.ins().iconst(clif_ty, const_val as i128 as i64),
229             _ => panic!(
230                 "CValue::const_val for non bool/integer/pointer type {:?} is not allowed",
231                 ty
232             ),
233         };
234
235         CValue::by_val(val, layout)
236     }
237
238     pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
239         CValue(self.0, layout)
240     }
241 }
242
243 /// A place where you can write a value to or read a value from
244 #[derive(Debug, Copy, Clone)]
245 pub struct CPlace<'tcx> {
246     inner: CPlaceInner,
247     layout: TyLayout<'tcx>,
248 }
249
250 #[derive(Debug, Copy, Clone)]
251 pub enum CPlaceInner {
252     Var(Local),
253     Addr(Pointer, Option<Value>),
254     NoPlace,
255 }
256
257 impl<'tcx> CPlace<'tcx> {
258     pub fn layout(&self) -> TyLayout<'tcx> {
259         self.layout
260     }
261
262     pub fn inner(&self) -> &CPlaceInner {
263         &self.inner
264     }
265
266     pub fn no_place(layout: TyLayout<'tcx>) -> CPlace<'tcx> {
267         CPlace {
268             inner: CPlaceInner::NoPlace,
269             layout,
270         }
271     }
272
273     pub fn new_stack_slot(
274         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
275         ty: Ty<'tcx>,
276     ) -> CPlace<'tcx> {
277         let layout = fx.layout_of(ty);
278         assert!(!layout.is_unsized());
279         if layout.size.bytes() == 0 {
280             return CPlace {
281                 inner: CPlaceInner::NoPlace,
282                 layout,
283             };
284         }
285
286         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
287             kind: StackSlotKind::ExplicitSlot,
288             size: layout.size.bytes() as u32,
289             offset: None,
290         });
291         CPlace {
292             inner: CPlaceInner::Addr(Pointer::stack_slot(stack_slot), None),
293             layout,
294         }
295     }
296
297     pub fn new_var(
298         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
299         local: Local,
300         layout: TyLayout<'tcx>,
301     ) -> CPlace<'tcx> {
302         fx.bcx
303             .declare_var(mir_var(local), fx.clif_type(layout.ty).unwrap());
304         CPlace {
305             inner: CPlaceInner::Var(local),
306             layout,
307         }
308     }
309
310     pub fn for_ptr(ptr: Pointer, layout: TyLayout<'tcx>) -> CPlace<'tcx> {
311         CPlace {
312             inner: CPlaceInner::Addr(ptr, None),
313             layout,
314         }
315     }
316
317     pub fn for_ptr_with_extra(ptr: Pointer, extra: Value, layout: TyLayout<'tcx>) -> CPlace<'tcx> {
318         CPlace {
319             inner: CPlaceInner::Addr(ptr, Some(extra)),
320             layout,
321         }
322     }
323
324     pub fn to_cvalue(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> CValue<'tcx> {
325         let layout = self.layout();
326         match self.inner {
327             CPlaceInner::Var(var) => {
328                 let val = fx.bcx.use_var(mir_var(var));
329                 fx.bcx.set_val_label(val, cranelift_codegen::ir::ValueLabel::from_u32(var.as_u32()));
330                 CValue::by_val(val, layout)
331             }
332             CPlaceInner::Addr(ptr, extra) => {
333                 assert!(extra.is_none(), "unsized values are not yet supported");
334                 CValue::by_ref(ptr, layout)
335             }
336             CPlaceInner::NoPlace => CValue::by_ref(
337                 Pointer::const_addr(fx, i64::try_from(self.layout.align.pref.bytes()).unwrap()),
338                 layout,
339             ),
340         }
341     }
342
343     pub fn to_ptr(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Pointer {
344         match self.to_ptr_maybe_unsized(fx) {
345             (ptr, None) => ptr,
346             (_, Some(_)) => bug!("Expected sized cplace, found {:?}", self),
347         }
348     }
349
350     pub fn to_ptr_maybe_unsized(
351         self,
352         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
353     ) -> (Pointer, Option<Value>) {
354         match self.inner {
355             CPlaceInner::Addr(ptr, extra) => (ptr, extra),
356             CPlaceInner::NoPlace => {
357                 (
358                     Pointer::const_addr(fx, i64::try_from(self.layout.align.pref.bytes()).unwrap()),
359                     None,
360                 )
361             }
362             CPlaceInner::Var(_) => bug!("Expected CPlace::Addr, found CPlace::Var"),
363         }
364     }
365
366     pub fn write_cvalue(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, from: CValue<'tcx>) {
367         #[cfg(debug_assertions)]
368         {
369             use cranelift_codegen::cursor::{Cursor, CursorPosition};
370             let cur_ebb = match fx.bcx.cursor().position() {
371                 CursorPosition::After(ebb) => ebb,
372                 _ => unreachable!(),
373             };
374             fx.add_comment(
375                 fx.bcx.func.layout.last_inst(cur_ebb).unwrap(),
376                 format!("write_cvalue: {:?} <- {:?}",self, from),
377             );
378         }
379
380         let from_ty = from.layout().ty;
381         let to_ty = self.layout().ty;
382
383         fn assert_assignable<'tcx>(
384             fx: &FunctionCx<'_, 'tcx, impl Backend>,
385             from_ty: Ty<'tcx>,
386             to_ty: Ty<'tcx>,
387         ) {
388             match (&from_ty.kind, &to_ty.kind) {
389                 (ty::Ref(_, t, Mutability::Not), ty::Ref(_, u, Mutability::Not))
390                 | (ty::Ref(_, t, Mutability::Mut), ty::Ref(_, u, Mutability::Not))
391                 | (ty::Ref(_, t, Mutability::Mut), ty::Ref(_, u, Mutability::Mut)) => {
392                     assert_assignable(fx, t, u);
393                     // &mut T -> &T is allowed
394                     // &'a T -> &'b T is allowed
395                 }
396                 (ty::Ref(_, _, Mutability::Not), ty::Ref(_, _, Mutability::Mut)) => panic!(
397                     "Cant assign value of type {} to place of type {}",
398                     from_ty, to_ty
399                 ),
400                 (ty::FnPtr(_), ty::FnPtr(_)) => {
401                     let from_sig = fx.tcx.normalize_erasing_late_bound_regions(
402                         ParamEnv::reveal_all(),
403                         &from_ty.fn_sig(fx.tcx),
404                     );
405                     let to_sig = fx.tcx.normalize_erasing_late_bound_regions(
406                         ParamEnv::reveal_all(),
407                         &to_ty.fn_sig(fx.tcx),
408                     );
409                     assert_eq!(
410                         from_sig, to_sig,
411                         "Can't write fn ptr with incompatible sig {:?} to place with sig {:?}\n\n{:#?}",
412                         from_sig, to_sig, fx,
413                     );
414                     // fn(&T) -> for<'l> fn(&'l T) is allowed
415                 }
416                 (ty::Dynamic(from_traits, _), ty::Dynamic(to_traits, _)) => {
417                     let from_traits = fx
418                         .tcx
419                         .normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), from_traits);
420                     let to_traits = fx
421                         .tcx
422                         .normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), to_traits);
423                     assert_eq!(
424                         from_traits, to_traits,
425                         "Can't write trait object of incompatible traits {:?} to place with traits {:?}\n\n{:#?}",
426                         from_traits, to_traits, fx,
427                     );
428                     // dyn for<'r> Trait<'r> -> dyn Trait<'_> is allowed
429                 }
430                 _ => {
431                     assert_eq!(
432                         from_ty,
433                         to_ty,
434                         "Can't write value with incompatible type {:?} to place with type {:?}\n\n{:#?}",
435                         from_ty,
436                         to_ty,
437                         fx,
438                     );
439                 }
440             }
441         }
442
443         assert_assignable(fx, from_ty, to_ty);
444
445         let dst_layout = self.layout();
446         let to_ptr = match self.inner {
447             CPlaceInner::Var(var) => {
448                 let data = from.load_scalar(fx);
449                 fx.bcx.set_val_label(data, cranelift_codegen::ir::ValueLabel::from_u32(var.as_u32()));
450                 fx.bcx.def_var(mir_var(var), data);
451                 return;
452             }
453             CPlaceInner::Addr(ptr, None) => ptr,
454             CPlaceInner::NoPlace => {
455                 if dst_layout.abi != Abi::Uninhabited {
456                     assert_eq!(dst_layout.size.bytes(), 0, "{:?}", dst_layout);
457                 }
458                 return;
459             }
460             CPlaceInner::Addr(_, Some(_)) => bug!("Can't write value to unsized place {:?}", self),
461         };
462
463         match from.0 {
464             CValueInner::ByVal(val) => {
465                 to_ptr.store(fx, val, MemFlags::new());
466             }
467             CValueInner::ByValPair(value, extra) => match dst_layout.abi {
468                 Abi::ScalarPair(ref a_scalar, ref b_scalar) => {
469                     let b_offset = scalar_pair_calculate_b_offset(fx.tcx, a_scalar, b_scalar);
470                     to_ptr.store(fx, value, MemFlags::new());
471                     to_ptr.offset(fx, b_offset).store(fx, extra, MemFlags::new());
472                 }
473                 _ => bug!(
474                     "Non ScalarPair abi {:?} for ByValPair CValue",
475                     dst_layout.abi
476                 ),
477             },
478             CValueInner::ByRef(from_ptr) => {
479                 let from_addr = from_ptr.get_addr(fx);
480                 let to_addr = to_ptr.get_addr(fx);
481                 let src_layout = from.1;
482                 let size = dst_layout.size.bytes();
483                 let src_align = src_layout.align.abi.bytes() as u8;
484                 let dst_align = dst_layout.align.abi.bytes() as u8;
485                 fx.bcx.emit_small_memcpy(
486                     fx.module.target_config(),
487                     to_addr,
488                     from_addr,
489                     size,
490                     dst_align,
491                     src_align,
492                 );
493             }
494         }
495     }
496
497     pub fn place_field(
498         self,
499         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
500         field: mir::Field,
501     ) -> CPlace<'tcx> {
502         let layout = self.layout();
503         let (base, extra) = self.to_ptr_maybe_unsized(fx);
504
505         let (field_ptr, field_layout) = codegen_field(fx, base, extra, layout, field);
506         if field_layout.is_unsized() {
507             CPlace::for_ptr_with_extra(field_ptr, extra.unwrap(), field_layout)
508         } else {
509             CPlace::for_ptr(field_ptr, field_layout)
510         }
511     }
512
513     pub fn place_index(
514         self,
515         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
516         index: Value,
517     ) -> CPlace<'tcx> {
518         let (elem_layout, ptr) = match self.layout().ty.kind {
519             ty::Array(elem_ty, _) => (fx.layout_of(elem_ty), self.to_ptr(fx)),
520             ty::Slice(elem_ty) => (fx.layout_of(elem_ty), self.to_ptr_maybe_unsized(fx).0),
521             _ => bug!("place_index({:?})", self.layout().ty),
522         };
523
524         let offset = fx
525             .bcx
526             .ins()
527             .imul_imm(index, elem_layout.size.bytes() as i64);
528
529         CPlace::for_ptr(ptr.offset_value(fx, offset), elem_layout)
530     }
531
532     pub fn place_deref(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> CPlace<'tcx> {
533         let inner_layout = fx.layout_of(self.layout().ty.builtin_deref(true).unwrap().ty);
534         if has_ptr_meta(fx.tcx, inner_layout.ty) {
535             let (addr, extra) = self.to_cvalue(fx).load_scalar_pair(fx);
536             CPlace::for_ptr_with_extra(Pointer::new(addr), extra, inner_layout)
537         } else {
538             CPlace::for_ptr(Pointer::new(self.to_cvalue(fx).load_scalar(fx)), inner_layout)
539         }
540     }
541
542     pub fn write_place_ref(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
543         if has_ptr_meta(fx.tcx, self.layout().ty) {
544             let (ptr, extra) = self.to_ptr_maybe_unsized(fx);
545             let ptr = CValue::by_val_pair(
546                 ptr.get_addr(fx),
547                 extra.expect("unsized type without metadata"),
548                 dest.layout(),
549             );
550             dest.write_cvalue(fx, ptr);
551         } else {
552             let ptr = CValue::by_val(self.to_ptr(fx).get_addr(fx), dest.layout());
553             dest.write_cvalue(fx, ptr);
554         }
555     }
556
557     pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
558         assert!(!self.layout().is_unsized());
559         match self.inner {
560             CPlaceInner::NoPlace => {
561                 assert!(layout.size.bytes() == 0);
562             }
563             _ => {}
564         }
565         CPlace {
566             inner: self.inner,
567             layout,
568         }
569     }
570
571     pub fn downcast_variant(
572         self,
573         fx: &FunctionCx<'_, 'tcx, impl Backend>,
574         variant: VariantIdx,
575     ) -> Self {
576         let layout = self.layout().for_variant(fx, variant);
577         self.unchecked_cast_to(layout)
578     }
579 }