4 use rustc_target::spec::abi::Abi;
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()),
14 println!("rust-call sig: {:?} inputs: {:?} output: {:?}", sig, sig.inputs(), sig.output());
15 let extra_args = match sig.inputs().last().unwrap().sty {
16 ty::TyTuple(ref tupled_arguments) => tupled_arguments,
17 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
19 let mut inputs: Vec<Ty> = sig.inputs()[0..sig.inputs().len() - 1].to_vec();
20 inputs.extend(extra_args.into_iter());
27 Abi::System => bug!("system abi should be selected elsewhere"),
28 // TODO: properly implement intrinsics
29 Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
30 _ => unimplemented!("unsupported abi {:?}", sig.abi),
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(),
42 fn ty_fn_sig<'a, 'tcx>(
43 tcx: TyCtxt<'a, 'tcx, 'tcx>,
45 ) -> ty::FnSig<'tcx> {
46 let sig = match ty.sty {
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);
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()),
62 ty::TyGenerator(def_id, substs, _) => {
63 let sig = substs.poly_sig(def_id, tcx);
65 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
66 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
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(&[
75 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
77 tcx.mk_fn_sig(iter::once(env_ty),
80 hir::Unsafety::Normal,
85 _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
87 tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
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());
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 module.declare_function(&tcx.absolute_item_path_str(inst.def_id()), Linkage::Local, &sig).unwrap()
101 module.declare_func_in_func(func_id, &mut self.bcx.func)
104 fn self_sig(&self) -> FnSig<'tcx> {
105 ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
108 fn return_type(&self) -> Ty<'tcx> {
109 self.self_sig().output()
113 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, start_ebb: Ebb) {
114 let ret_param = fx.bcx.append_ebb_param(start_ebb, types::I64);
115 let _ = fx.bcx.create_stack_slot(StackSlotData {
116 kind: StackSlotKind::ExplicitSlot,
119 }); // Dummy stack slot for debugging
121 let func_params = fx.mir.args_iter().map(|local| {
122 let layout = fx.layout_of(fx.mir.local_decls[local].ty);
123 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
124 kind: StackSlotKind::ExplicitSlot,
125 size: layout.size.bytes() as u32,
128 let ty = fx.mir.local_decls[local].ty;
129 let cton_type = fx.cton_type(ty).unwrap_or(types::I64);
130 (local, fx.bcx.append_ebb_param(start_ebb, cton_type), ty, stack_slot)
131 }).collect::<Vec<(Local, Value, Ty, StackSlot)>>();
133 let ret_layout = fx.layout_of(fx.return_type());
134 fx.local_map.insert(RETURN_PLACE, CPlace::Addr(ret_param, ret_layout));
136 for (local, ebb_param, ty, stack_slot) in func_params {
137 let place = CPlace::from_stack_slot(fx, stack_slot, ty);
138 if fx.cton_type(ty).is_some() {
139 place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()));
141 place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout()));
143 fx.local_map.insert(local, place);
146 for local in fx.mir.vars_and_temps_iter() {
147 let ty = fx.mir.local_decls[local].ty;
148 let layout = fx.layout_of(ty);
149 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
150 kind: StackSlotKind::ExplicitSlot,
151 size: layout.size.bytes() as u32,
154 let place = CPlace::from_stack_slot(fx, stack_slot, ty);
155 fx.local_map.insert(local, place);
159 pub fn codegen_call<'a, 'tcx: 'a>(
160 fx: &mut FunctionCx<'a, 'tcx>,
161 func: &Operand<'tcx>,
162 args: &[Operand<'tcx>],
163 destination: &Option<(Place<'tcx>, BasicBlock)>,
165 let func = ::base::trans_operand(fx, func);
166 let fn_ty = func.layout().ty;
167 let sig = ty_fn_sig(fx.tcx, fn_ty);
169 let return_place = if let Some((place, _)) = destination {
170 Some(::base::trans_place(fx, place))
175 // Unpack arguments tuple for closures
176 let args = if sig.abi == Abi::RustCall {
177 assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
178 let self_arg = ::base::trans_operand(fx, &args[0]);
179 let pack_arg = ::base::trans_operand(fx, &args[1]);
180 let mut args = Vec::new();
182 match pack_arg.layout().ty.sty {
183 ty::TyTuple(ref tupled_arguments) => {
184 for (i, _) in tupled_arguments.iter().enumerate() {
185 args.push(pack_arg.value_field(fx, mir::Field::new(i)));
188 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
195 ::base::trans_operand(fx, arg)
200 if let TypeVariants::TyFnDef(def_id, substs) = fn_ty.sty {
201 if sig.abi == Abi::RustIntrinsic {
202 let intrinsic = fx.tcx.item_name(def_id).as_str();
203 let intrinsic = &intrinsic[..];
205 let usize_layout = fx.layout_of(fx.tcx.types.usize);
206 let ret = return_place.unwrap();
209 /*let elem_ty = substs.type_at(0);
210 assert_eq!(args.len(), 3);
213 let count = args[2];*/
214 unimplemented!("copy");
217 assert_eq!(args.len(), 0);
218 let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
219 let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
220 ret.write_cvalue(fx, size_of);
222 _ if intrinsic.starts_with("unchecked_") => {
223 assert_eq!(args.len(), 2);
224 let lhs = args[0].load_value(fx);
225 let rhs = args[1].load_value(fx);
226 let bin_op = match intrinsic {
227 "unchecked_div" => BinOp::Div,
228 "unchecked_rem" => BinOp::Rem,
229 "unchecked_shl" => BinOp::Shl,
230 "unchecked_shr" => BinOp::Shr,
231 _ => unimplemented!("intrinsic {}", intrinsic),
233 let res = match ret.layout().ty.sty {
234 TypeVariants::TyUint(_) => {
235 ::base::trans_int_binop(fx, bin_op, lhs, rhs, args[0].layout().ty, false, false)
237 TypeVariants::TyInt(_) => {
238 ::base::trans_int_binop(fx, bin_op, lhs, rhs, args[0].layout().ty, true, false)
242 ret.write_cvalue(fx, res);
245 assert_eq!(args.len(), 2);
246 let base = args[0].load_value(fx);
247 let offset = args[1].load_value(fx);
248 let res = fx.bcx.ins().iadd(base, offset);
249 ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
252 assert_eq!(args.len(), 1);
253 let src_ty = substs.type_at(0);
254 let dst_ty = substs.type_at(1);
255 assert_eq!(args[0].layout().ty, src_ty);
256 let addr = args[0].force_stack(fx);
257 let dst_layout = fx.layout_of(dst_ty);
258 ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
260 _ => fx.tcx.sess.fatal(&format!("unsupported intrinsic {}", intrinsic)),
262 if let Some((_, dest)) = *destination {
263 let ret_ebb = fx.get_ebb(dest);
264 fx.bcx.ins().jump(ret_ebb, &[]);
266 fx.bcx.ins().trap(TrapCode::User(!0));
272 let return_ptr = match return_place {
273 Some(place) => place.expect_addr(),
274 None => fx.bcx.ins().iconst(types::I64, 0),
277 let call_args = Some(return_ptr).into_iter().chain(args.into_iter().map(|arg| {
278 if fx.cton_type(arg.layout().ty).is_some() {
283 })).collect::<Vec<_>>();
286 CValue::Func(func, _) => {
287 fx.bcx.ins().call(func, &call_args);
290 let func_ty = func.layout().ty;
291 let func = func.load_value(fx);
292 let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, func_ty));
293 fx.bcx.ins().call_indirect(sig, func, &call_args);
296 if let Some((_, dest)) = *destination {
297 let ret_ebb = fx.get_ebb(dest);
298 fx.bcx.ins().jump(ret_ebb, &[]);
300 fx.bcx.ins().trap(TrapCode::User(!0));