]> git.lizzy.rs Git - rust.git/blob - src/common.rs
Implement char to uint cast
[rust.git] / src / common.rs
1 extern crate rustc_target;
2
3 use std::borrow::Cow;
4 use std::fmt;
5
6 use syntax::ast::{IntTy, UintTy};
7 use self::rustc_target::spec::{HasTargetSpec, Target};
8
9 use cranelift_module::{Module, FuncId, DataId};
10
11 use prelude::*;
12
13 pub type CurrentBackend = ::cranelift_simplejit::SimpleJITBackend;
14
15 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
16 pub struct Variable(Local);
17
18 impl EntityRef for Variable {
19     fn new(u: usize) -> Self {
20         Variable(Local::new(u))
21     }
22
23     fn index(self) -> usize {
24         self.0.index()
25     }
26 }
27
28 pub fn cton_type_from_ty<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> Option<types::Type> {
29     Some(match ty.sty {
30         TypeVariants::TyBool => types::I8,
31         TypeVariants::TyUint(size) => {
32             match size {
33                 UintTy::U8 => types::I8,
34                 UintTy::U16 => types::I16,
35                 UintTy::U32 => types::I32,
36                 UintTy::U64 => types::I64,
37                 UintTy::U128 => unimplemented!("u128"),
38                 UintTy::Usize => types::I64,
39             }
40         }
41         TypeVariants::TyInt(size) => {
42             match size {
43                 IntTy::I8 => types::I8,
44                 IntTy::I16 => types::I16,
45                 IntTy::I32 => types::I32,
46                 IntTy::I64 => types::I64,
47                 IntTy::I128 => unimplemented!("i128"),
48                 IntTy::Isize => types::I64,
49             }
50         }
51         TypeVariants::TyChar => types::I32,
52         TypeVariants::TyFnPtr(_) => types::I64,
53         TypeVariants::TyRawPtr(TypeAndMut { ty, mutbl: _ }) | TypeVariants::TyRef(_, ty, _) => {
54             if ty.is_sized(tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
55                 types::I64
56             } else {
57                 return None;
58             }
59         }
60         TypeVariants::TyParam(_)  => bug!("{:?}: {:?}", ty, ty.sty),
61         _ => return None,
62     })
63 }
64
65 /// A read-only value
66 #[derive(Debug, Copy, Clone)]
67 pub enum CValue<'tcx> {
68     ByRef(Value, TyLayout<'tcx>),
69     ByVal(Value, TyLayout<'tcx>),
70     Func(FuncRef, TyLayout<'tcx>),
71 }
72
73 impl<'tcx> CValue<'tcx> {
74     pub fn layout(&self) -> TyLayout<'tcx> {
75         match *self {
76             CValue::ByRef(_, layout) |
77             CValue::ByVal(_, layout) |
78             CValue::Func(_, layout) => layout
79         }
80     }
81
82     pub fn force_stack<'a>(self, fx: &mut FunctionCx<'a, 'tcx>) -> Value where 'tcx: 'a {
83         match self {
84             CValue::ByRef(value, _layout) => value,
85             CValue::ByVal(value, layout) => {
86                 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
87                     kind: StackSlotKind::ExplicitSlot,
88                     size: layout.size.bytes() as u32,
89                     offset: None,
90                 });
91                 fx.bcx.ins().stack_store(value, stack_slot, 0);
92                 fx.bcx.ins().stack_addr(types::I64, stack_slot, 0)
93             }
94             CValue::Func(func, ty) => {
95                 let func = fx.bcx.ins().func_addr(types::I64, func);
96                 CValue::ByVal(func, ty).force_stack(fx)
97             }
98         }
99     }
100
101     pub fn load_value<'a>(self, fx: &mut FunctionCx<'a, 'tcx>) -> Value where 'tcx: 'a{
102         match self {
103             CValue::ByRef(addr, layout) => {
104                 let cton_ty = fx.cton_type(layout.ty).expect(&format!("load_value of type {:?}", layout.ty));
105                 fx.bcx.ins().load(cton_ty, MemFlags::new(), addr, 0)
106             }
107             CValue::ByVal(value, _layout) => value,
108             CValue::Func(func, _layout) => {
109                 fx.bcx.ins().func_addr(types::I64, func)
110             }
111         }
112     }
113
114     pub fn expect_byref(self) -> (Value, TyLayout<'tcx>) {
115         match self {
116             CValue::ByRef(value, layout) => (value, layout),
117             CValue::ByVal(_, _) => bug!("Expected CValue::ByRef, found CValue::ByVal"),
118             CValue::Func(_, _) => bug!("Expected CValue::ByRef, found CValue::Func"),
119         }
120     }
121
122     pub fn value_field<'a>(self, fx: &mut FunctionCx<'a, 'tcx>, field: mir::Field) -> CValue<'tcx> where 'tcx: 'a {
123         use rustc::ty::util::IntTypeExt;
124
125         let (base, layout) = match self {
126             CValue::ByRef(addr, layout) => (addr, layout),
127             _ => bug!("place_field for {:?}", self),
128         };
129         let field_offset = layout.fields.offset(field.index());
130         let field_layout = if field.index() == 0 {
131             fx.layout_of(if let ty::TyAdt(adt_def, _) = layout.ty.sty {
132                 adt_def.repr.discr_type().to_ty(fx.tcx)
133             } else {
134                 // This can only be `0`, for now, so `u8` will suffice.
135                 fx.tcx.types.u8
136             })
137         } else {
138             layout.field(&*fx, field.index())
139         };
140         if field_offset.bytes() > 0 {
141             let field_offset = fx.bcx.ins().iconst(types::I64, field_offset.bytes() as i64);
142             CValue::ByRef(fx.bcx.ins().iadd(base, field_offset), field_layout)
143         } else {
144             CValue::ByRef(base, field_layout)
145         }
146     }
147
148     pub fn const_val<'a>(fx: &mut FunctionCx<'a, 'tcx>, ty: Ty<'tcx>, const_val: i64) -> CValue<'tcx> where 'tcx: 'a {
149         let cton_ty = fx.cton_type(ty).unwrap();
150         let layout = fx.layout_of(ty);
151         CValue::ByVal(fx.bcx.ins().iconst(cton_ty, const_val), layout)
152     }
153
154     pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
155         match self {
156             CValue::ByRef(addr, _) => CValue::ByRef(addr, layout),
157             CValue::ByVal(val, _) => CValue::ByVal(val, layout),
158             CValue::Func(fun, _) => CValue::Func(fun, layout),
159         }
160     }
161 }
162
163 /// A place where you can write a value to or read a value from
164 #[derive(Debug, Copy, Clone)]
165 pub enum CPlace<'tcx> {
166     Var(Variable, TyLayout<'tcx>),
167     Addr(Value, TyLayout<'tcx>),
168 }
169
170 impl<'a, 'tcx: 'a> CPlace<'tcx> {
171     pub fn layout(&self) -> TyLayout<'tcx> {
172         match *self {
173             CPlace::Var(_, layout) |
174             CPlace::Addr(_, layout) => layout
175         }
176     }
177
178     pub fn from_stack_slot(fx: &mut FunctionCx<'a, 'tcx>, stack_slot: StackSlot, ty: Ty<'tcx>) -> CPlace<'tcx> {
179         let layout = fx.layout_of(ty);
180         CPlace::Addr(fx.bcx.ins().stack_addr(types::I64, stack_slot, 0), layout)
181     }
182
183     pub fn to_cvalue(self, fx: &mut FunctionCx<'a, 'tcx>) -> CValue<'tcx> {
184         match self {
185             CPlace::Var(var, layout) => CValue::ByVal(fx.bcx.use_var(var), layout),
186             CPlace::Addr(addr, layout) => CValue::ByRef(addr, layout),
187         }
188     }
189
190     pub fn expect_addr(self) -> Value {
191         match self {
192             CPlace::Addr(addr, _layout) => addr,
193             CPlace::Var(_, _) => bug!("Expected CPlace::Addr, found CPlace::Var"),
194         }
195     }
196
197     pub fn write_cvalue(self, fx: &mut FunctionCx<'a, 'tcx>, from: CValue<'tcx>) {
198         match (&self.layout().ty.sty, &from.layout().ty.sty) {
199             (TypeVariants::TyRef(_, t, dest_mut), TypeVariants::TyRef(_, u, src_mut)) if (
200                 if *dest_mut != ::rustc::hir::Mutability::MutImmutable && src_mut != dest_mut {
201                     false
202                 } else if t != u {
203                     false
204                 } else {
205                     true
206                 }
207             ) => {
208                 // &mut T -> &T is allowed
209                 // &'a T -> &'b T is allowed
210             }
211             _ => {
212                 assert_eq!(
213                     self.layout().ty, from.layout().ty,
214                     "Can't write value of incompatible type to place {:?} {:?}\n\n{:#?}",
215                     self.layout().ty.sty, from.layout().ty.sty,
216                     fx,
217                 );
218             }
219         }
220
221         match self {
222             CPlace::Var(var, _) => {
223                 let data = from.load_value(fx);
224                 fx.bcx.def_var(var, data)
225             },
226             CPlace::Addr(addr, layout) => {
227                 let size = layout.size.bytes() as i32;
228
229                 if let Some(_) = fx.cton_type(layout.ty) {
230                     let data = from.load_value(fx);
231                     fx.bcx.ins().store(MemFlags::new(), data, addr, 0);
232                 } else {
233                     let from = from.expect_byref();
234                     let mut offset = 0;
235                     while size - offset >= 8 {
236                         let byte = fx.bcx.ins().load(types::I64, MemFlags::new(), from.0, offset);
237                         fx.bcx.ins().store(MemFlags::new(), byte, addr, offset);
238                         offset += 8;
239                     }
240                     while size - offset >= 4 {
241                         let byte = fx.bcx.ins().load(types::I32, MemFlags::new(), from.0, offset);
242                         fx.bcx.ins().store(MemFlags::new(), byte, addr, offset);
243                         offset += 4;
244                     }
245                     while offset < size {
246                         let byte = fx.bcx.ins().load(types::I8, MemFlags::new(), from.0, offset);
247                         fx.bcx.ins().store(MemFlags::new(), byte, addr, offset);
248                         offset += 1;
249                     }
250                 }
251             }
252         }
253     }
254
255     pub fn place_field(self, fx: &mut FunctionCx<'a, 'tcx>, field: mir::Field) -> CPlace<'tcx> {
256         let base = self.expect_addr();
257         let layout = self.layout();
258         let field_offset = layout.fields.offset(field.index());
259         let field_ty = layout.field(&*fx, field.index());
260         if field_offset.bytes() > 0 {
261             let field_offset = fx.bcx.ins().iconst(types::I64, field_offset.bytes() as i64);
262             CPlace::Addr(fx.bcx.ins().iadd(base, field_offset), field_ty)
263         } else {
264             fx.bcx.ins().nop();
265             CPlace::Addr(base, field_ty)
266         }
267     }
268
269     pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
270         match self {
271             CPlace::Var(var, _) => CPlace::Var(var, layout),
272             CPlace::Addr(addr, _) => CPlace::Addr(addr, layout),
273         }
274     }
275
276     pub fn downcast_variant(self, fx: &FunctionCx<'a, 'tcx>, variant: usize) -> Self {
277         let layout = self.layout().for_variant(fx, variant);
278         self.unchecked_cast_to(layout)
279     }
280 }
281
282 pub fn cton_intcast<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, val: Value, from: Ty<'tcx>, to: Ty<'tcx>, signed: bool) -> Value {
283     let from = fx.cton_type(from).unwrap();
284     let to = fx.cton_type(to).unwrap();
285     if from == to {
286         return val;
287     }
288     if to.wider_or_equal(from) {
289         if signed {
290             fx.bcx.ins().sextend(to, val)
291         } else {
292             fx.bcx.ins().uextend(to, val)
293         }
294     } else {
295         fx.bcx.ins().ireduce(to, val)
296     }
297 }
298
299 pub struct FunctionCx<'a, 'tcx: 'a> {
300     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
301     pub module: &'a mut Module<CurrentBackend>,
302     pub def_id_fn_id_map: &'a mut HashMap<Instance<'tcx>, FuncId>,
303     pub instance: Instance<'tcx>,
304     pub mir: &'tcx Mir<'tcx>,
305     pub param_substs: &'tcx Substs<'tcx>,
306     pub bcx: FunctionBuilder<'a, Variable>,
307     pub ebb_map: HashMap<BasicBlock, Ebb>,
308     pub local_map: HashMap<Local, CPlace<'tcx>>,
309     pub comments: HashMap<Inst, String>,
310     pub constants: &'a mut HashMap<AllocId, DataId>,
311 }
312
313 impl<'a, 'tcx: 'a> fmt::Debug for FunctionCx<'a, 'tcx> {
314     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
315         writeln!(f, "{:?}", self.def_id_fn_id_map)?;
316         writeln!(f, "{:?}", self.param_substs)?;
317         writeln!(f, "{:?}", self.local_map)?;
318
319         let mut clif = String::new();
320         let mut writer = ::pretty_clif::CommentWriter(self.comments.clone());
321         ::cranelift::codegen::write::decorate_function(
322             &mut writer,
323             &mut clif,
324             &self.bcx.func,
325             None,
326         ).unwrap();
327         writeln!(f, "\n{}", clif)
328     }
329 }
330
331 impl<'a, 'tcx: 'a> LayoutOf for &'a FunctionCx<'a, 'tcx> {
332     type Ty = Ty<'tcx>;
333     type TyLayout = TyLayout<'tcx>;
334
335     fn layout_of(self, ty: Ty<'tcx>) -> TyLayout<'tcx> {
336         let ty = self.monomorphize(&ty);
337         self.tcx.layout_of(ParamEnv::reveal_all().and(&ty)).unwrap()
338     }
339 }
340
341 impl<'a, 'tcx> layout::HasTyCtxt<'tcx> for &'a FunctionCx<'a, 'tcx> {
342     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
343         self.tcx
344     }
345 }
346
347 impl<'a, 'tcx> layout::HasDataLayout for &'a FunctionCx<'a, 'tcx> {
348     fn data_layout(&self) -> &layout::TargetDataLayout {
349         &self.tcx.data_layout
350     }
351 }
352
353 impl<'a, 'tcx> HasTargetSpec for &'a FunctionCx<'a, 'tcx> {
354     fn target_spec(&self) -> &Target {
355         &self.tcx.sess.target.target
356     }
357 }
358
359 impl<'a, 'tcx: 'a> FunctionCx<'a, 'tcx> {
360     pub fn monomorphize<T>(&self, value: &T) -> T
361         where T: TypeFoldable<'tcx>
362     {
363         self.tcx.subst_and_normalize_erasing_regions(
364             self.param_substs,
365             ty::ParamEnv::reveal_all(),
366             value,
367         )
368     }
369
370     pub fn cton_type(&self, ty: Ty<'tcx>) -> Option<Type> {
371         cton_type_from_ty(self.tcx, self.monomorphize(&ty))
372     }
373
374     pub fn get_ebb(&self, bb: BasicBlock) -> Ebb {
375         *self.ebb_map.get(&bb).unwrap()
376     }
377
378     pub fn get_local_place(&mut self, local: Local) -> CPlace<'tcx> {
379         *self.local_map.get(&local).unwrap()
380     }
381
382     pub fn add_comment<'s, S: Into<Cow<'s, str>>>(&mut self, inst: Inst, comment: S) {
383         use std::collections::hash_map::Entry;
384         match self.comments.entry(inst) {
385             Entry::Occupied(mut occ) => {
386                 occ.get_mut().push('\n');
387                 occ.get_mut().push_str(comment.into().as_ref());
388             }
389             Entry::Vacant(vac) => {
390                 vac.insert(comment.into().into_owned());
391             }
392         }
393     }
394 }