]> git.lizzy.rs Git - rust.git/blob - src/abi.rs
Implement some intrinsics
[rust.git] / src / abi.rs
1 use std::iter;
2
3 use rustc::hir;
4 use rustc_target::spec::abi::Abi;
5
6 use prelude::*;
7
8 pub fn cton_sig_from_fn_ty<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn_ty: Ty<'tcx>) -> Signature {
9     let sig = ty_fn_sig(tcx, fn_ty);
10     assert!(!sig.variadic, "Variadic function are not yet supported");
11     let (call_conv, inputs, _output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
12         Abi::Rust => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
13         Abi::RustCall => {
14             println!("rust-call sig: {:?} inputs: {:?} output: {:?}", sig, sig.inputs(), sig.output());
15             assert_eq!(sig.inputs().len(), 2);
16             let extra_args = match sig.inputs().last().unwrap().sty {
17                 ty::TyTuple(ref tupled_arguments) => tupled_arguments,
18                 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
19             };
20             let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
21             inputs.extend(extra_args.into_iter());
22             (
23                 CallConv::SystemV,
24                 inputs,
25                 sig.output(),
26             )
27         }
28         Abi::System => bug!("system abi should be selected elsewhere"),
29         Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
30         _ => unimplemented!("unsupported abi {:?}", sig.abi),
31     };
32     Signature {
33         params: Some(types::I64).into_iter() // First param is place to put return val
34             .chain(inputs.into_iter().map(|ty| cton_type_from_ty(tcx, ty).unwrap_or(types::I64)))
35             .map(AbiParam::new).collect(),
36         returns: vec![],
37         call_conv,
38         argument_bytes: None,
39     }
40 }
41
42 fn ty_fn_sig<'a, 'tcx>(
43     tcx: TyCtxt<'a, 'tcx, 'tcx>,
44     ty: Ty<'tcx>
45 ) -> ty::FnSig<'tcx> {
46     let sig = match ty.sty {
47         ty::TyFnDef(..) |
48         // Shims currently have type TyFnPtr. Not sure this should remain.
49         ty::TyFnPtr(_) => ty.fn_sig(tcx),
50         ty::TyClosure(def_id, substs) => {
51             let sig = substs.closure_sig(def_id, tcx);
52
53             let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
54             sig.map_bound(|sig| tcx.mk_fn_sig(
55                 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
56                 sig.output(),
57                 sig.variadic,
58                 sig.unsafety,
59                 sig.abi
60             ))
61         }
62         ty::TyGenerator(def_id, substs, _) => {
63             let sig = substs.poly_sig(def_id, tcx);
64
65             let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
66             let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
67
68             sig.map_bound(|sig| {
69                 let state_did = tcx.lang_items().gen_state().unwrap();
70                 let state_adt_ref = tcx.adt_def(state_did);
71                 let state_substs = tcx.intern_substs(&[
72                     sig.yield_ty.into(),
73                     sig.return_ty.into(),
74                 ]);
75                 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
76
77                 tcx.mk_fn_sig(iter::once(env_ty),
78                     ret_ty,
79                     false,
80                     hir::Unsafety::Normal,
81                     Abi::Rust
82                 )
83             })
84         }
85         _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
86     };
87     tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
88 }
89
90 impl<'a, 'tcx: 'a> FunctionCx<'a, 'tcx> {
91     /// Instance must be monomorphized
92     pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
93         assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
94         let tcx = self.tcx;
95         let module = &mut self.module;
96         let func_id = *self.def_id_fn_id_map.entry(inst).or_insert_with(|| {
97             let fn_ty = inst.ty(tcx);
98             let sig = cton_sig_from_fn_ty(tcx, fn_ty);
99             let def_path_based_names = ::rustc_mir::monomorphize::item::DefPathBasedNames::new(tcx, false, false);
100             let mut name = String::new();
101             def_path_based_names.push_instance_as_string(inst, &mut name);
102             module.declare_function(&name, Linkage::Local, &sig).unwrap()
103         });
104         module.declare_func_in_func(func_id, &mut self.bcx.func)
105     }
106
107     fn self_sig(&self) -> FnSig<'tcx> {
108         ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
109     }
110
111     fn return_type(&self) -> Ty<'tcx> {
112         self.self_sig().output()
113     }
114 }
115
116 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, start_ebb: Ebb) {
117     let ret_param = fx.bcx.append_ebb_param(start_ebb, types::I64);
118     let _ = fx.bcx.create_stack_slot(StackSlotData {
119         kind: StackSlotKind::ExplicitSlot,
120         size: 0,
121         offset: None,
122     }); // Dummy stack slot for debugging
123
124     enum ArgKind {
125         Normal(Value),
126         Spread(Vec<Value>),
127     }
128
129     let func_params = fx.mir.args_iter().map(|local| {
130         let arg_ty = fx.mir.local_decls[local].ty;
131
132         // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
133         if Some(local) == fx.mir.spread_arg {
134             // This argument (e.g. the last argument in the "rust-call" ABI)
135             // is a tuple that was spread at the ABI level and now we have
136             // to reconstruct it into a tuple local variable, from multiple
137             // individual function arguments.
138
139             let tupled_arg_tys = match arg_ty.sty {
140                 ty::TyTuple(ref tys) => tys,
141                 _ => bug!("spread argument isn't a tuple?!")
142             };
143
144             let mut ebb_params = Vec::new();
145             for arg_ty in tupled_arg_tys.iter() {
146                 let cton_type = fx.cton_type(arg_ty).unwrap_or(types::I64);
147                 ebb_params.push(fx.bcx.append_ebb_param(start_ebb, cton_type));
148             }
149
150             (local, ArgKind::Spread(ebb_params), arg_ty)
151         } else {
152             let cton_type = fx.cton_type(arg_ty).unwrap_or(types::I64);
153             (local, ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, cton_type)), arg_ty)
154         }
155     }).collect::<Vec<(Local, ArgKind, Ty)>>();
156
157     let ret_layout = fx.layout_of(fx.return_type());
158     fx.local_map.insert(RETURN_PLACE, CPlace::Addr(ret_param, ret_layout));
159
160     for (local, arg_kind, ty) in func_params {
161         let layout = fx.layout_of(ty);
162         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
163             kind: StackSlotKind::ExplicitSlot,
164             size: layout.size.bytes() as u32,
165             offset: None,
166         });
167
168         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
169
170         match arg_kind {
171             ArgKind::Normal(ebb_param) => {
172                 if fx.cton_type(ty).is_some() {
173                     place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()));
174                 } else {
175                     place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout()));
176                 }
177             }
178             ArgKind::Spread(ebb_params) => {
179                 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
180                     let sub_place = place.place_field(fx, mir::Field::new(i));
181                     if fx.cton_type(sub_place.layout().ty).is_some() {
182                         sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()));
183                     } else {
184                         sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()));
185                     }
186                 }
187             }
188         }
189         fx.local_map.insert(local, place);
190     }
191
192     for local in fx.mir.vars_and_temps_iter() {
193         let ty = fx.mir.local_decls[local].ty;
194         let layout = fx.layout_of(ty);
195         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
196             kind: StackSlotKind::ExplicitSlot,
197             size: layout.size.bytes() as u32,
198             offset: None,
199         });
200         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
201         fx.local_map.insert(local, place);
202     }
203 }
204
205 pub fn codegen_call<'a, 'tcx: 'a>(
206     fx: &mut FunctionCx<'a, 'tcx>,
207     func: &Operand<'tcx>,
208     args: &[Operand<'tcx>],
209     destination: &Option<(Place<'tcx>, BasicBlock)>,
210 ) {
211     let func = ::base::trans_operand(fx, func);
212     let fn_ty = func.layout().ty;
213     let sig = ty_fn_sig(fx.tcx, fn_ty);
214
215     let return_place = if let Some((place, _)) = destination {
216         Some(::base::trans_place(fx, place))
217     } else {
218         None
219     };
220
221     // Unpack arguments tuple for closures
222     let args = if sig.abi == Abi::RustCall {
223         assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
224         let self_arg = ::base::trans_operand(fx, &args[0]);
225         let pack_arg = ::base::trans_operand(fx, &args[1]);
226         let mut args = Vec::new();
227         args.push(self_arg);
228         match pack_arg.layout().ty.sty {
229             ty::TyTuple(ref tupled_arguments) => {
230                 for (i, _) in tupled_arguments.iter().enumerate() {
231                     args.push(pack_arg.value_field(fx, mir::Field::new(i)));
232                 }
233             },
234             _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
235         }
236         println!("{:?} {:?}", pack_arg.layout().ty, args.iter().map(|a|a.layout().ty).collect::<Vec<_>>());
237         args
238     } else {
239         args
240             .into_iter()
241             .map(|arg| {
242                 ::base::trans_operand(fx, arg)
243             })
244             .collect::<Vec<_>>()
245     };
246
247     if let TypeVariants::TyFnDef(def_id, substs) = fn_ty.sty {
248         if sig.abi == Abi::RustIntrinsic {
249             let intrinsic = fx.tcx.item_name(def_id).as_str();
250             let intrinsic = &intrinsic[..];
251
252             let usize_layout = fx.layout_of(fx.tcx.types.usize);
253             let ret = return_place.unwrap();
254             match intrinsic {
255                 "abort" => {
256                     fx.bcx.ins().trap(TrapCode::User(!0 - 1));
257                 }
258                 "copy" | "copy_nonoverlapping" => {
259                     /*let elem_ty = substs.type_at(0);
260                     assert_eq!(args.len(), 3);
261                     let src = args[0];
262                     let dst = args[1];
263                     let count = args[2];*/
264                     unimplemented!("copy");
265                 }
266                 "size_of" => {
267                     assert_eq!(args.len(), 0);
268                     let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
269                     let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
270                     ret.write_cvalue(fx, size_of);
271                 }
272                 "type_id" => {
273                     assert_eq!(args.len(), 0);
274                     let type_id = fx.tcx.type_id_hash(substs.type_at(0));
275                     let type_id = CValue::const_val(fx, usize_layout.ty, type_id as i64);
276                     ret.write_cvalue(fx, type_id);
277                 }
278                 "min_align_of" => {
279                     assert_eq!(args.len(), 0);
280                     let min_align = fx.layout_of(substs.type_at(0)).align.abi();
281                     let min_align = CValue::const_val(fx, usize_layout.ty, min_align as i64);
282                     ret.write_cvalue(fx, min_align);
283                 }
284                 _ if intrinsic.starts_with("unchecked_") => {
285                     assert_eq!(args.len(), 2);
286                     let lhs = args[0].load_value(fx);
287                     let rhs = args[1].load_value(fx);
288                     let bin_op = match intrinsic {
289                         "unchecked_div" => BinOp::Div,
290                         "unchecked_rem" => BinOp::Rem,
291                         "unchecked_shl" => BinOp::Shl,
292                         "unchecked_shr" => BinOp::Shr,
293                         _ => unimplemented!("intrinsic {}", intrinsic),
294                     };
295                     let res = match ret.layout().ty.sty {
296                         TypeVariants::TyUint(_) => {
297                             ::base::trans_int_binop(fx, bin_op, lhs, rhs, args[0].layout().ty, false, false)
298                         }
299                         TypeVariants::TyInt(_) => {
300                             ::base::trans_int_binop(fx, bin_op, lhs, rhs, args[0].layout().ty, true, false)
301                         }
302                         _ => panic!(),
303                     };
304                     ret.write_cvalue(fx, res);
305                 }
306                 "offset" => {
307                     assert_eq!(args.len(), 2);
308                     let base = args[0].load_value(fx);
309                     let offset = args[1].load_value(fx);
310                     let res = fx.bcx.ins().iadd(base, offset);
311                     ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
312                 }
313                 "transmute" => {
314                     assert_eq!(args.len(), 1);
315                     let src_ty = substs.type_at(0);
316                     let dst_ty = substs.type_at(1);
317                     assert_eq!(args[0].layout().ty, src_ty);
318                     let addr = args[0].force_stack(fx);
319                     let dst_layout = fx.layout_of(dst_ty);
320                     ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
321                 }
322                 "uninit" => {
323                     assert_eq!(args.len(), 0);
324                     let ty = substs.type_at(0);
325                     let layout = fx.layout_of(ty);
326                     let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
327                         kind: StackSlotKind::ExplicitSlot,
328                         size: layout.size.bytes() as u32,
329                         offset: None,
330                     });
331
332                     let uninit_place = CPlace::from_stack_slot(fx, stack_slot, ty);
333                     let uninit_val = uninit_place.to_cvalue(fx);
334                     ret.write_cvalue(fx, uninit_val);
335                 }
336                 _ => fx.tcx.sess.fatal(&format!("unsupported intrinsic {}", intrinsic)),
337             }
338             if let Some((_, dest)) = *destination {
339                 let ret_ebb = fx.get_ebb(dest);
340                 fx.bcx.ins().jump(ret_ebb, &[]);
341             } else {
342                 fx.bcx.ins().trap(TrapCode::User(!0));
343             }
344             return;
345         }
346     }
347
348     let return_ptr = match return_place {
349         Some(place) => place.expect_addr(),
350         None => fx.bcx.ins().iconst(types::I64, 0),
351     };
352
353     let call_args = Some(return_ptr).into_iter().chain(args.into_iter().map(|arg| {
354         if fx.cton_type(arg.layout().ty).is_some() {
355             arg.load_value(fx)
356         } else {
357             arg.force_stack(fx)
358         }
359     })).collect::<Vec<_>>();
360
361     match func {
362         CValue::Func(func, _) => {
363             fx.bcx.ins().call(func, &call_args);
364         }
365         func => {
366             let func_ty = func.layout().ty;
367             let func = func.load_value(fx);
368             let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, func_ty));
369             fx.bcx.ins().call_indirect(sig, func, &call_args);
370         }
371     }
372     if let Some((_, dest)) = *destination {
373         let ret_ebb = fx.get_ebb(dest);
374         fx.bcx.ins().jump(ret_ebb, &[]);
375     } else {
376         fx.bcx.ins().trap(TrapCode::User(!0));
377     }
378 }