]> git.lizzy.rs Git - rust.git/blob - src/abi.rs
Add some basic intrinsic support (only size_of atm)
[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     let sig = tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig);
11     assert!(!sig.variadic, "Variadic function are not yet supported");
12     let (call_conv, inputs, _output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
13         Abi::Rust => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
14         Abi::RustCall => {
15             unimplemented!("rust-call");
16         }
17         Abi::System => bug!("system abi should be selected elsewhere"),
18         // TODO: properly implement intrinsics
19         Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
20         _ => unimplemented!("unsupported abi {:?}", sig.abi),
21     };
22     Signature {
23         params: Some(types::I64).into_iter() // First param is place to put return val
24             .chain(inputs.into_iter().map(|ty| cton_type_from_ty(tcx, ty).unwrap_or(types::I64)))
25             .map(AbiParam::new).collect(),
26         returns: vec![],
27         call_conv,
28         argument_bytes: None,
29     }
30 }
31
32 fn ty_fn_sig<'a, 'tcx>(
33     tcx: TyCtxt<'a, 'tcx, 'tcx>,
34     ty: Ty<'tcx>
35 ) -> ty::PolyFnSig<'tcx> {
36     match ty.sty {
37         ty::TyFnDef(..) |
38         // Shims currently have type TyFnPtr. Not sure this should remain.
39         ty::TyFnPtr(_) => ty.fn_sig(tcx),
40         ty::TyClosure(def_id, substs) => {
41             let sig = substs.closure_sig(def_id, tcx);
42
43             let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
44             sig.map_bound(|sig| tcx.mk_fn_sig(
45                 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
46                 sig.output(),
47                 sig.variadic,
48                 sig.unsafety,
49                 sig.abi
50             ))
51         }
52         ty::TyGenerator(def_id, substs, _) => {
53             let sig = substs.poly_sig(def_id, tcx);
54
55             let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
56             let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
57
58             sig.map_bound(|sig| {
59                 let state_did = tcx.lang_items().gen_state().unwrap();
60                 let state_adt_ref = tcx.adt_def(state_did);
61                 let state_substs = tcx.intern_substs(&[
62                     sig.yield_ty.into(),
63                     sig.return_ty.into(),
64                 ]);
65                 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
66
67                 tcx.mk_fn_sig(iter::once(env_ty),
68                     ret_ty,
69                     false,
70                     hir::Unsafety::Normal,
71                     Abi::Rust
72                 )
73             })
74         }
75         _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
76     }
77 }
78
79 impl<'a, 'tcx: 'a> FunctionCx<'a, 'tcx> {
80     /// Instance must be monomorphized
81     pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
82         assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
83         let tcx = self.tcx;
84         let module = &mut self.module;
85         let func_id = *self.def_id_fn_id_map.entry(inst).or_insert_with(|| {
86             let fn_ty = inst.ty(tcx);
87             let sig = cton_sig_from_fn_ty(tcx, fn_ty);
88             module.declare_function(&tcx.absolute_item_path_str(inst.def_id()), Linkage::Local, &sig).unwrap()
89         });
90         module.declare_func_in_func(func_id, &mut self.bcx.func)
91     }
92
93     fn self_sig(&self) -> FnSig<'tcx> {
94         let sig = ty_fn_sig(self.tcx, self.instance.ty(self.tcx));
95         self.tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
96     }
97
98     fn return_type(&self) -> Ty<'tcx> {
99         self.self_sig().output()
100     }
101 }
102
103 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, start_ebb: Ebb) {
104     let ret_param = fx.bcx.append_ebb_param(start_ebb, types::I64);
105     let _ = fx.bcx.create_stack_slot(StackSlotData {
106         kind: StackSlotKind::ExplicitSlot,
107         size: 0,
108         offset: None,
109     }); // Dummy stack slot for debugging
110
111     let func_params = fx.mir.args_iter().map(|local| {
112         let layout = fx.layout_of(fx.mir.local_decls[local].ty);
113         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
114             kind: StackSlotKind::ExplicitSlot,
115             size: layout.size.bytes() as u32,
116             offset: None,
117         });
118         let ty = fx.mir.local_decls[local].ty;
119         let cton_type = fx.cton_type(ty).unwrap_or(types::I64);
120         (local, fx.bcx.append_ebb_param(start_ebb, cton_type), ty, stack_slot)
121     }).collect::<Vec<(Local, Value, Ty, StackSlot)>>();
122
123     let ret_layout = fx.layout_of(fx.return_type());
124     fx.local_map.insert(RETURN_PLACE, CPlace::Addr(ret_param, ret_layout));
125
126     for (local, ebb_param, ty, stack_slot) in func_params {
127         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
128         if fx.cton_type(ty).is_some() {
129             place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()));
130         } else {
131             place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout()));
132         }
133         fx.local_map.insert(local, place);
134     }
135
136     for local in fx.mir.vars_and_temps_iter() {
137         let ty = fx.mir.local_decls[local].ty;
138         let layout = fx.layout_of(ty);
139         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
140             kind: StackSlotKind::ExplicitSlot,
141             size: layout.size.bytes() as u32,
142             offset: None,
143         });
144         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
145         fx.local_map.insert(local, place);
146     }
147 }
148
149 pub fn codegen_call<'a, 'tcx: 'a>(
150     fx: &mut FunctionCx<'a, 'tcx>,
151     func: &Operand<'tcx>,
152     args: &[Operand<'tcx>],
153     destination: &Option<(Place<'tcx>, BasicBlock)>,
154 ) {
155     let func = ::base::trans_operand(fx, func);
156
157     let return_place = if let Some((place, _)) = destination {
158         Some(::base::trans_place(fx, place))
159     } else {
160         None
161     };
162
163     let args = args
164         .into_iter()
165         .map(|arg| {
166             let arg = ::base::trans_operand(fx, arg);
167             if let Some(_) = fx.cton_type(arg.layout().ty) {
168                 arg.load_value(fx)
169             } else {
170                 arg.force_stack(fx)
171             }
172         })
173         .collect::<Vec<_>>();
174
175     let fn_ty = func.layout().ty;
176     if let TypeVariants::TyFnDef(def_id, substs) = fn_ty.sty {
177         let instance = ty::Instance::resolve(
178             fx.tcx,
179             ParamEnv::reveal_all(),
180             def_id,
181             substs
182         ).unwrap();
183
184         // Handle intrinsics old codegen wants Expr's for, ourselves.
185         if let InstanceDef::Intrinsic(def_id) = instance.def {
186             let intrinsic = fx.tcx.item_name(def_id).as_str();
187             let intrinsic = &intrinsic[..];
188
189             let usize_layout = fx.layout_of(fx.tcx.types.usize);
190             match intrinsic {
191                 "copy" => {
192                     /*let elem_ty = substs.type_at(0);
193                     assert_eq!(args.len(), 3);
194                     let src = args[0];
195                     let dst = args[1];
196                     let count = args[2];*/
197                     unimplemented!("copy");
198                 }
199                 "size_of" => {
200                     let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
201                     let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
202                     return_place.unwrap().write_cvalue(fx, size_of);
203                 }
204                 _ => fx.tcx.sess.fatal(&format!("unsupported intrinsic {}", intrinsic)),
205             }
206             if let Some((_, dest)) = *destination {
207                 let ret_ebb = fx.get_ebb(dest);
208                 fx.bcx.ins().jump(ret_ebb, &[]);
209             } else {
210                 fx.bcx.ins().trap(TrapCode::User(!0));
211             }
212             return;
213         }
214     }
215
216     let return_ptr = match return_place {
217         Some(place) => place.expect_addr(),
218         None => fx.bcx.ins().iconst(types::I64, 0),
219     };
220
221     let args = Some(return_ptr).into_iter().chain(args).collect::<Vec<_>>();
222
223     match func {
224         CValue::Func(func, _) => {
225             fx.bcx.ins().call(func, &args);
226         }
227         func => {
228             let func_ty = func.layout().ty;
229             let func = func.load_value(fx);
230             let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, func_ty));
231             fx.bcx.ins().call_indirect(sig, func, &args);
232         }
233     }
234     if let Some((_, dest)) = *destination {
235         let ret_ebb = fx.get_ebb(dest);
236         fx.bcx.ins().jump(ret_ebb, &[]);
237     } else {
238         fx.bcx.ins().trap(TrapCode::User(!0));
239     }
240 }