]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/cast.rs
Update src/libcore/mem.rs
[rust.git] / src / librustc_mir / interpret / cast.rs
1 use rustc::ty::{self, Ty, TypeAndMut};
2 use rustc::ty::layout::{self, TyLayout, Size};
3 use rustc::ty::adjustment::{PointerCast};
4 use syntax::ast::{FloatTy, IntTy, UintTy};
5 use syntax::symbol::sym;
6
7 use rustc_apfloat::ieee::{Single, Double};
8 use rustc::mir::interpret::{
9     Scalar, EvalResult, Pointer, PointerArithmetic, InterpError, truncate
10 };
11 use rustc::mir::CastKind;
12 use rustc_apfloat::Float;
13
14 use super::{InterpretCx, Machine, PlaceTy, OpTy, ImmTy, Immediate};
15
16 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> InterpretCx<'a, 'mir, 'tcx, M> {
17     fn type_is_fat_ptr(&self, ty: Ty<'tcx>) -> bool {
18         match ty.sty {
19             ty::RawPtr(ty::TypeAndMut { ty, .. }) |
20             ty::Ref(_, ty, _) => !self.type_is_sized(ty),
21             ty::Adt(def, _) if def.is_box() => !self.type_is_sized(ty.boxed_ty()),
22             _ => false,
23         }
24     }
25
26     pub fn cast(
27         &mut self,
28         src: OpTy<'tcx, M::PointerTag>,
29         kind: CastKind,
30         dest: PlaceTy<'tcx, M::PointerTag>,
31     ) -> EvalResult<'tcx> {
32         use rustc::mir::CastKind::*;
33         match kind {
34             Pointer(PointerCast::Unsize) => {
35                 self.unsize_into(src, dest)?;
36             }
37
38             Misc | Pointer(PointerCast::MutToConstPointer) => {
39                 let src = self.read_immediate(src)?;
40
41                 if self.type_is_fat_ptr(src.layout.ty) {
42                     match (*src, self.type_is_fat_ptr(dest.layout.ty)) {
43                         // pointers to extern types
44                         (Immediate::Scalar(_),_) |
45                         // slices and trait objects to other slices/trait objects
46                         (Immediate::ScalarPair(..), true) => {
47                             // No change to immediate
48                             self.write_immediate(*src, dest)?;
49                         }
50                         // slices and trait objects to thin pointers (dropping the metadata)
51                         (Immediate::ScalarPair(data, _), false) => {
52                             self.write_scalar(data, dest)?;
53                         }
54                     }
55                 } else {
56                     match src.layout.variants {
57                         layout::Variants::Single { index } => {
58                             if let Some(discr) =
59                                 src.layout.ty.discriminant_for_variant(*self.tcx, index)
60                             {
61                                 // Cast from a univariant enum
62                                 assert!(src.layout.is_zst());
63                                 return self.write_scalar(
64                                     Scalar::from_uint(discr.val, dest.layout.size),
65                                     dest);
66                             }
67                         }
68                         layout::Variants::Multiple { .. } => {},
69                     }
70
71                     let dest_val = self.cast_scalar(src.to_scalar()?, src.layout, dest.layout)?;
72                     self.write_scalar(dest_val, dest)?;
73                 }
74             }
75
76             Pointer(PointerCast::ReifyFnPointer) => {
77                 // The src operand does not matter, just its type
78                 match src.layout.ty.sty {
79                     ty::FnDef(def_id, substs) => {
80                         if self.tcx.has_attr(def_id, sym::rustc_args_required_const) {
81                             bug!("reifying a fn ptr that requires const arguments");
82                         }
83                         let instance: EvalResult<'tcx, _> = ty::Instance::resolve(
84                             *self.tcx,
85                             self.param_env,
86                             def_id,
87                             substs,
88                         ).ok_or_else(|| InterpError::TooGeneric.into());
89                         let fn_ptr = self.memory.create_fn_alloc(instance?).with_default_tag();
90                         self.write_scalar(Scalar::Ptr(fn_ptr.into()), dest)?;
91                     }
92                     _ => bug!("reify fn pointer on {:?}", src.layout.ty),
93                 }
94             }
95
96             Pointer(PointerCast::UnsafeFnPointer) => {
97                 let src = self.read_immediate(src)?;
98                 match dest.layout.ty.sty {
99                     ty::FnPtr(_) => {
100                         // No change to value
101                         self.write_immediate(*src, dest)?;
102                     }
103                     _ => bug!("fn to unsafe fn cast on {:?}", dest.layout.ty),
104                 }
105             }
106
107             Pointer(PointerCast::ClosureFnPointer(_)) => {
108                 // The src operand does not matter, just its type
109                 match src.layout.ty.sty {
110                     ty::Closure(def_id, substs) => {
111                         let substs = self.subst_and_normalize_erasing_regions(substs)?;
112                         let instance = ty::Instance::resolve_closure(
113                             *self.tcx,
114                             def_id,
115                             substs,
116                             ty::ClosureKind::FnOnce,
117                         );
118                         let fn_ptr = self.memory.create_fn_alloc(instance).with_default_tag();
119                         let val = Immediate::Scalar(Scalar::Ptr(fn_ptr.into()).into());
120                         self.write_immediate(val, dest)?;
121                     }
122                     _ => bug!("closure fn pointer on {:?}", src.layout.ty),
123                 }
124             }
125         }
126         Ok(())
127     }
128
129     pub(super) fn cast_scalar(
130         &self,
131         val: Scalar<M::PointerTag>,
132         src_layout: TyLayout<'tcx>,
133         dest_layout: TyLayout<'tcx>,
134     ) -> EvalResult<'tcx, Scalar<M::PointerTag>> {
135         use rustc::ty::TyKind::*;
136         trace!("Casting {:?}: {:?} to {:?}", val, src_layout.ty, dest_layout.ty);
137
138         match val {
139             Scalar::Ptr(ptr) => self.cast_from_ptr(ptr, dest_layout.ty),
140             Scalar::Bits { bits, size } => {
141                 debug_assert_eq!(size as u64, src_layout.size.bytes());
142                 debug_assert_eq!(truncate(bits, Size::from_bytes(size.into())), bits,
143                     "Unexpected value of size {} before casting", size);
144
145                 let res = match src_layout.ty.sty {
146                     Float(fty) => self.cast_from_float(bits, fty, dest_layout.ty)?,
147                     _ => self.cast_from_int(bits, src_layout, dest_layout)?,
148                 };
149
150                 // Sanity check
151                 match res {
152                     Scalar::Ptr(_) => bug!("Fabricated a ptr value from an int...?"),
153                     Scalar::Bits { bits, size } => {
154                         debug_assert_eq!(size as u64, dest_layout.size.bytes());
155                         debug_assert_eq!(truncate(bits, Size::from_bytes(size.into())), bits,
156                             "Unexpected value of size {} after casting", size);
157                     }
158                 }
159                 // Done
160                 Ok(res)
161             }
162         }
163     }
164
165     fn cast_from_int(
166         &self,
167         v: u128,
168         src_layout: TyLayout<'tcx>,
169         dest_layout: TyLayout<'tcx>,
170     ) -> EvalResult<'tcx, Scalar<M::PointerTag>> {
171         let signed = src_layout.abi.is_signed();
172         let v = if signed {
173             self.sign_extend(v, src_layout)
174         } else {
175             v
176         };
177         trace!("cast_from_int: {}, {}, {}", v, src_layout.ty, dest_layout.ty);
178         use rustc::ty::TyKind::*;
179         match dest_layout.ty.sty {
180             Int(_) | Uint(_) => {
181                 let v = self.truncate(v, dest_layout);
182                 Ok(Scalar::from_uint(v, dest_layout.size))
183             }
184
185             Float(FloatTy::F32) if signed => Ok(Scalar::from_uint(
186                 Single::from_i128(v as i128).value.to_bits(),
187                 Size::from_bits(32)
188             )),
189             Float(FloatTy::F64) if signed => Ok(Scalar::from_uint(
190                 Double::from_i128(v as i128).value.to_bits(),
191                 Size::from_bits(64)
192             )),
193             Float(FloatTy::F32) => Ok(Scalar::from_uint(
194                 Single::from_u128(v).value.to_bits(),
195                 Size::from_bits(32)
196             )),
197             Float(FloatTy::F64) => Ok(Scalar::from_uint(
198                 Double::from_u128(v).value.to_bits(),
199                 Size::from_bits(64)
200             )),
201
202             Char => {
203                 // `u8` to `char` cast
204                 debug_assert_eq!(v as u8 as u128, v);
205                 Ok(Scalar::from_uint(v, Size::from_bytes(4)))
206             },
207
208             // No alignment check needed for raw pointers.
209             // But we have to truncate to target ptr size.
210             RawPtr(_) => {
211                 Ok(Scalar::from_uint(
212                     self.truncate_to_ptr(v).0,
213                     self.pointer_size(),
214                 ))
215             },
216
217             // Casts to bool are not permitted by rustc, no need to handle them here.
218             _ => err!(Unimplemented(format!("int to {:?} cast", dest_layout.ty))),
219         }
220     }
221
222     fn cast_from_float(
223         &self,
224         bits: u128,
225         fty: FloatTy,
226         dest_ty: Ty<'tcx>
227     ) -> EvalResult<'tcx, Scalar<M::PointerTag>> {
228         use rustc::ty::TyKind::*;
229         use rustc_apfloat::FloatConvert;
230         match dest_ty.sty {
231             // float -> uint
232             Uint(t) => {
233                 let width = t.bit_width().unwrap_or_else(|| self.pointer_size().bits() as usize);
234                 let v = match fty {
235                     FloatTy::F32 => Single::from_bits(bits).to_u128(width).value,
236                     FloatTy::F64 => Double::from_bits(bits).to_u128(width).value,
237                 };
238                 // This should already fit the bit width
239                 Ok(Scalar::from_uint(v, Size::from_bits(width as u64)))
240             },
241             // float -> int
242             Int(t) => {
243                 let width = t.bit_width().unwrap_or_else(|| self.pointer_size().bits() as usize);
244                 let v = match fty {
245                     FloatTy::F32 => Single::from_bits(bits).to_i128(width).value,
246                     FloatTy::F64 => Double::from_bits(bits).to_i128(width).value,
247                 };
248                 Ok(Scalar::from_int(v, Size::from_bits(width as u64)))
249             },
250             // f64 -> f32
251             Float(FloatTy::F32) if fty == FloatTy::F64 => {
252                 Ok(Scalar::from_uint(
253                     Single::to_bits(Double::from_bits(bits).convert(&mut false).value),
254                     Size::from_bits(32),
255                 ))
256             },
257             // f32 -> f64
258             Float(FloatTy::F64) if fty == FloatTy::F32 => {
259                 Ok(Scalar::from_uint(
260                     Double::to_bits(Single::from_bits(bits).convert(&mut false).value),
261                     Size::from_bits(64),
262                 ))
263             },
264             // identity cast
265             Float(FloatTy:: F64) => Ok(Scalar::from_uint(bits, Size::from_bits(64))),
266             Float(FloatTy:: F32) => Ok(Scalar::from_uint(bits, Size::from_bits(32))),
267             _ => err!(Unimplemented(format!("float to {:?} cast", dest_ty))),
268         }
269     }
270
271     fn cast_from_ptr(
272         &self,
273         ptr: Pointer<M::PointerTag>,
274         ty: Ty<'tcx>
275     ) -> EvalResult<'tcx, Scalar<M::PointerTag>> {
276         use rustc::ty::TyKind::*;
277         match ty.sty {
278             // Casting to a reference or fn pointer is not permitted by rustc,
279             // no need to support it here.
280             RawPtr(_) |
281             Int(IntTy::Isize) |
282             Uint(UintTy::Usize) => Ok(ptr.into()),
283             Int(_) | Uint(_) => err!(ReadPointerAsBytes),
284             _ => err!(Unimplemented(format!("ptr to {:?} cast", ty))),
285         }
286     }
287
288     fn unsize_into_ptr(
289         &mut self,
290         src: OpTy<'tcx, M::PointerTag>,
291         dest: PlaceTy<'tcx, M::PointerTag>,
292         // The pointee types
293         sty: Ty<'tcx>,
294         dty: Ty<'tcx>,
295     ) -> EvalResult<'tcx> {
296         // A<Struct> -> A<Trait> conversion
297         let (src_pointee_ty, dest_pointee_ty) = self.tcx.struct_lockstep_tails(sty, dty);
298
299         match (&src_pointee_ty.sty, &dest_pointee_ty.sty) {
300             (&ty::Array(_, length), &ty::Slice(_)) => {
301                 let ptr = self.read_immediate(src)?.to_scalar_ptr()?;
302                 // u64 cast is from usize to u64, which is always good
303                 let val = Immediate::new_slice(
304                     ptr,
305                     length.unwrap_usize(self.tcx.tcx),
306                     self,
307                 );
308                 self.write_immediate(val, dest)
309             }
310             (&ty::Dynamic(..), &ty::Dynamic(..)) => {
311                 // For now, upcasts are limited to changes in marker
312                 // traits, and hence never actually require an actual
313                 // change to the vtable.
314                 let val = self.read_immediate(src)?;
315                 self.write_immediate(*val, dest)
316             }
317             (_, &ty::Dynamic(ref data, _)) => {
318                 // Initial cast from sized to dyn trait
319                 let vtable = self.get_vtable(src_pointee_ty, data.principal())?;
320                 let ptr = self.read_immediate(src)?.to_scalar_ptr()?;
321                 let val = Immediate::new_dyn_trait(ptr, vtable);
322                 self.write_immediate(val, dest)
323             }
324
325             _ => bug!("invalid unsizing {:?} -> {:?}", src.layout.ty, dest.layout.ty),
326         }
327     }
328
329     fn unsize_into(
330         &mut self,
331         src: OpTy<'tcx, M::PointerTag>,
332         dest: PlaceTy<'tcx, M::PointerTag>,
333     ) -> EvalResult<'tcx> {
334         match (&src.layout.ty.sty, &dest.layout.ty.sty) {
335             (&ty::Ref(_, s, _), &ty::Ref(_, d, _)) |
336             (&ty::Ref(_, s, _), &ty::RawPtr(TypeAndMut { ty: d, .. })) |
337             (&ty::RawPtr(TypeAndMut { ty: s, .. }),
338              &ty::RawPtr(TypeAndMut { ty: d, .. })) => {
339                 self.unsize_into_ptr(src, dest, s, d)
340             }
341             (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
342                 assert_eq!(def_a, def_b);
343                 if def_a.is_box() || def_b.is_box() {
344                     if !def_a.is_box() || !def_b.is_box() {
345                         bug!("invalid unsizing between {:?} -> {:?}", src.layout, dest.layout);
346                     }
347                     return self.unsize_into_ptr(
348                         src,
349                         dest,
350                         src.layout.ty.boxed_ty(),
351                         dest.layout.ty.boxed_ty(),
352                     );
353                 }
354
355                 // unsizing of generic struct with pointer fields
356                 // Example: `Arc<T>` -> `Arc<Trait>`
357                 // here we need to increase the size of every &T thin ptr field to a fat ptr
358                 for i in 0..src.layout.fields.count() {
359                     let dst_field = self.place_field(dest, i as u64)?;
360                     if dst_field.layout.is_zst() {
361                         continue;
362                     }
363                     let src_field = match src.try_as_mplace() {
364                         Ok(mplace) => {
365                             let src_field = self.mplace_field(mplace, i as u64)?;
366                             src_field.into()
367                         }
368                         Err(..) => {
369                             let src_field_layout = src.layout.field(self, i)?;
370                             // this must be a field covering the entire thing
371                             assert_eq!(src.layout.fields.offset(i).bytes(), 0);
372                             assert_eq!(src_field_layout.size, src.layout.size);
373                             // just sawp out the layout
374                             OpTy::from(ImmTy { imm: src.to_immediate(), layout: src_field_layout })
375                         }
376                     };
377                     if src_field.layout.ty == dst_field.layout.ty {
378                         self.copy_op(src_field, dst_field)?;
379                     } else {
380                         self.unsize_into(src_field, dst_field)?;
381                     }
382                 }
383                 Ok(())
384             }
385             _ => {
386                 bug!(
387                     "unsize_into: invalid conversion: {:?} -> {:?}",
388                     src.layout,
389                     dest.layout
390                 )
391             }
392         }
393     }
394 }