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