]> git.lizzy.rs Git - rust.git/blob - src/abi.rs
Add support for binop rem on floats
[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     pub fn lib_call(
108         &mut self,
109         name: &str,
110         input_tys: Vec<types::Type>,
111         output_ty: types::Type,
112         args: &[Value],
113     ) -> Value {
114         let sig = Signature {
115             params: input_tys.iter().cloned().map(AbiParam::new).collect(),
116             returns: vec![AbiParam::new(output_ty)],
117             call_conv: CallConv::SystemV,
118             argument_bytes: None,
119         };
120         let func_id = self.module.declare_function(&name, Linkage::Import, &sig).unwrap();
121         let func_ref = self.module.declare_func_in_func(func_id, &mut self.bcx.func);
122         let call_inst = self.bcx.ins().call(func_ref, args);
123         let results = self.bcx.inst_results(call_inst);
124         assert_eq!(results.len(), 1);
125         results[0]
126     }
127
128     pub fn easy_call(&mut self, name: &str, args: &[CValue<'tcx>], return_ty: Ty<'tcx>) -> CValue<'tcx> {
129         let (input_tys, args): (Vec<_>, Vec<_>) = args.into_iter().map(|arg| (self.cton_type(arg.layout().ty).unwrap(), arg.load_value(self))).unzip();
130         let return_layout = self.layout_of(return_ty);
131         let return_ty = self.cton_type(return_ty).unwrap();
132         CValue::ByVal(self.lib_call(name, input_tys, return_ty, &args), return_layout)
133     }
134
135     fn self_sig(&self) -> FnSig<'tcx> {
136         ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
137     }
138
139     fn return_type(&self) -> Ty<'tcx> {
140         self.self_sig().output()
141     }
142 }
143
144 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, start_ebb: Ebb) {
145     let ret_param = fx.bcx.append_ebb_param(start_ebb, types::I64);
146     let _ = fx.bcx.create_stack_slot(StackSlotData {
147         kind: StackSlotKind::ExplicitSlot,
148         size: 0,
149         offset: None,
150     }); // Dummy stack slot for debugging
151
152     enum ArgKind {
153         Normal(Value),
154         Spread(Vec<Value>),
155     }
156
157     let func_params = fx.mir.args_iter().map(|local| {
158         let arg_ty = fx.mir.local_decls[local].ty;
159
160         // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
161         if Some(local) == fx.mir.spread_arg {
162             // This argument (e.g. the last argument in the "rust-call" ABI)
163             // is a tuple that was spread at the ABI level and now we have
164             // to reconstruct it into a tuple local variable, from multiple
165             // individual function arguments.
166
167             let tupled_arg_tys = match arg_ty.sty {
168                 ty::TyTuple(ref tys) => tys,
169                 _ => bug!("spread argument isn't a tuple?!")
170             };
171
172             let mut ebb_params = Vec::new();
173             for arg_ty in tupled_arg_tys.iter() {
174                 let cton_type = fx.cton_type(arg_ty).unwrap_or(types::I64);
175                 ebb_params.push(fx.bcx.append_ebb_param(start_ebb, cton_type));
176             }
177
178             (local, ArgKind::Spread(ebb_params), arg_ty)
179         } else {
180             let cton_type = fx.cton_type(arg_ty).unwrap_or(types::I64);
181             (local, ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, cton_type)), arg_ty)
182         }
183     }).collect::<Vec<(Local, ArgKind, Ty)>>();
184
185     let ret_layout = fx.layout_of(fx.return_type());
186     fx.local_map.insert(RETURN_PLACE, CPlace::Addr(ret_param, ret_layout));
187
188     for (local, arg_kind, ty) in func_params {
189         let layout = fx.layout_of(ty);
190         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
191             kind: StackSlotKind::ExplicitSlot,
192             size: layout.size.bytes() as u32,
193             offset: None,
194         });
195
196         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
197
198         match arg_kind {
199             ArgKind::Normal(ebb_param) => {
200                 if fx.cton_type(ty).is_some() {
201                     place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()));
202                 } else {
203                     place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout()));
204                 }
205             }
206             ArgKind::Spread(ebb_params) => {
207                 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
208                     let sub_place = place.place_field(fx, mir::Field::new(i));
209                     if fx.cton_type(sub_place.layout().ty).is_some() {
210                         sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()));
211                     } else {
212                         sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()));
213                     }
214                 }
215             }
216         }
217         fx.local_map.insert(local, place);
218     }
219
220     for local in fx.mir.vars_and_temps_iter() {
221         let ty = fx.mir.local_decls[local].ty;
222         let layout = fx.layout_of(ty);
223         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
224             kind: StackSlotKind::ExplicitSlot,
225             size: layout.size.bytes() as u32,
226             offset: None,
227         });
228         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
229         fx.local_map.insert(local, place);
230     }
231 }
232
233 pub fn codegen_call<'a, 'tcx: 'a>(
234     fx: &mut FunctionCx<'a, 'tcx>,
235     func: &Operand<'tcx>,
236     args: &[Operand<'tcx>],
237     destination: &Option<(Place<'tcx>, BasicBlock)>,
238 ) {
239     let func = ::base::trans_operand(fx, func);
240     let fn_ty = func.layout().ty;
241     let sig = ty_fn_sig(fx.tcx, fn_ty);
242
243     let return_place = if let Some((place, _)) = destination {
244         Some(::base::trans_place(fx, place))
245     } else {
246         None
247     };
248
249     // Unpack arguments tuple for closures
250     let args = if sig.abi == Abi::RustCall {
251         assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
252         let self_arg = ::base::trans_operand(fx, &args[0]);
253         let pack_arg = ::base::trans_operand(fx, &args[1]);
254         let mut args = Vec::new();
255         args.push(self_arg);
256         match pack_arg.layout().ty.sty {
257             ty::TyTuple(ref tupled_arguments) => {
258                 for (i, _) in tupled_arguments.iter().enumerate() {
259                     args.push(pack_arg.value_field(fx, mir::Field::new(i)));
260                 }
261             },
262             _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
263         }
264         println!("{:?} {:?}", pack_arg.layout().ty, args.iter().map(|a|a.layout().ty).collect::<Vec<_>>());
265         args
266     } else {
267         args
268             .into_iter()
269             .map(|arg| {
270                 ::base::trans_operand(fx, arg)
271             })
272             .collect::<Vec<_>>()
273     };
274
275     if let TypeVariants::TyFnDef(def_id, substs) = fn_ty.sty {
276         if sig.abi == Abi::RustIntrinsic {
277             let intrinsic = fx.tcx.item_name(def_id).as_str();
278             let intrinsic = &intrinsic[..];
279
280             let usize_layout = fx.layout_of(fx.tcx.types.usize);
281             let ret = return_place.unwrap();
282             match intrinsic {
283                 "abort" => {
284                     fx.bcx.ins().trap(TrapCode::User(!0 - 1));
285                 }
286                 "copy" | "copy_nonoverlapping" => {
287                     /*let elem_ty = substs.type_at(0);
288                     assert_eq!(args.len(), 3);
289                     let src = args[0];
290                     let dst = args[1];
291                     let count = args[2];*/
292                     unimplemented!("copy");
293                 }
294                 "discriminant_value" => {
295                     assert_eq!(args.len(), 1);
296                     let discr = ::base::trans_get_discriminant(fx, args[0], ret.layout());
297                     ret.write_cvalue(fx, discr);
298                 }
299                 "size_of" => {
300                     assert_eq!(args.len(), 0);
301                     let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
302                     let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
303                     ret.write_cvalue(fx, size_of);
304                 }
305                 "type_id" => {
306                     assert_eq!(args.len(), 0);
307                     let type_id = fx.tcx.type_id_hash(substs.type_at(0));
308                     let type_id = CValue::const_val(fx, usize_layout.ty, type_id as i64);
309                     ret.write_cvalue(fx, type_id);
310                 }
311                 "min_align_of" => {
312                     assert_eq!(args.len(), 0);
313                     let min_align = fx.layout_of(substs.type_at(0)).align.abi();
314                     let min_align = CValue::const_val(fx, usize_layout.ty, min_align as i64);
315                     ret.write_cvalue(fx, min_align);
316                 }
317                 _ if intrinsic.starts_with("unchecked_") => {
318                     assert_eq!(args.len(), 2);
319                     let bin_op = match intrinsic {
320                         "unchecked_div" => BinOp::Div,
321                         "unchecked_rem" => BinOp::Rem,
322                         "unchecked_shl" => BinOp::Shl,
323                         "unchecked_shr" => BinOp::Shr,
324                         _ => unimplemented!("intrinsic {}", intrinsic),
325                     };
326                     let res = match ret.layout().ty.sty {
327                         TypeVariants::TyUint(_) => {
328                             ::base::trans_int_binop(fx, bin_op, args[0], args[1], ret.layout().ty, false, false)
329                         }
330                         TypeVariants::TyInt(_) => {
331                             ::base::trans_int_binop(fx, bin_op, args[0], args[1], ret.layout().ty, true, false)
332                         }
333                         _ => panic!(),
334                     };
335                     ret.write_cvalue(fx, res);
336                 }
337                 "offset" => {
338                     assert_eq!(args.len(), 2);
339                     let base = args[0].load_value(fx);
340                     let offset = args[1].load_value(fx);
341                     let res = fx.bcx.ins().iadd(base, offset);
342                     ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
343                 }
344                 "transmute" => {
345                     assert_eq!(args.len(), 1);
346                     let src_ty = substs.type_at(0);
347                     let dst_ty = substs.type_at(1);
348                     assert_eq!(args[0].layout().ty, src_ty);
349                     let addr = args[0].force_stack(fx);
350                     let dst_layout = fx.layout_of(dst_ty);
351                     ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
352                 }
353                 "uninit" => {
354                     assert_eq!(args.len(), 0);
355                     let ty = substs.type_at(0);
356                     let layout = fx.layout_of(ty);
357                     let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
358                         kind: StackSlotKind::ExplicitSlot,
359                         size: layout.size.bytes() as u32,
360                         offset: None,
361                     });
362
363                     let uninit_place = CPlace::from_stack_slot(fx, stack_slot, ty);
364                     let uninit_val = uninit_place.to_cvalue(fx);
365                     ret.write_cvalue(fx, uninit_val);
366                 }
367                 _ => fx.tcx.sess.fatal(&format!("unsupported intrinsic {}", intrinsic)),
368             }
369             if let Some((_, dest)) = *destination {
370                 let ret_ebb = fx.get_ebb(dest);
371                 fx.bcx.ins().jump(ret_ebb, &[]);
372             } else {
373                 fx.bcx.ins().trap(TrapCode::User(!0));
374             }
375             return;
376         }
377     }
378
379     let return_ptr = match return_place {
380         Some(place) => place.expect_addr(),
381         None => fx.bcx.ins().iconst(types::I64, 0),
382     };
383
384     let call_args = Some(return_ptr).into_iter().chain(args.into_iter().map(|arg| {
385         if fx.cton_type(arg.layout().ty).is_some() {
386             arg.load_value(fx)
387         } else {
388             arg.force_stack(fx)
389         }
390     })).collect::<Vec<_>>();
391
392     match func {
393         CValue::Func(func, _) => {
394             fx.bcx.ins().call(func, &call_args);
395         }
396         func => {
397             let func_ty = func.layout().ty;
398             let func = func.load_value(fx);
399             let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, func_ty));
400             fx.bcx.ins().call_indirect(sig, func, &call_args);
401         }
402     }
403     if let Some((_, dest)) = *destination {
404         let ret_ebb = fx.get_ebb(dest);
405         fx.bcx.ins().jump(ret_ebb, &[]);
406     } else {
407         fx.bcx.ins().trap(TrapCode::User(!0));
408     }
409 }