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