4 use rustc_target::spec::abi::Abi;
16 fn get_param_ty(self, fx: &FunctionCx<impl Backend>) -> Type {
18 PassMode::NoPass => unimplemented!("pass mode nopass"),
19 PassMode::ByVal(cton_type) => cton_type,
20 PassMode::ByRef => fx.pointer_type,
25 fn get_pass_mode<'a, 'tcx: 'a>(
26 tcx: TyCtxt<'a, 'tcx, 'tcx>,
32 .layout_of(ParamEnv::reveal_all().and(ty))
35 if let ty::Never = ty.sty {
41 } else if ty.sty == tcx.mk_unit().sty {
47 } else if let Some(ret_ty) = crate::common::cton_type_from_ty(tcx, ty) {
48 PassMode::ByVal(ret_ty)
52 "Non scalars are not yet supported for \"C\" abi ({:?}) is_return: {:?}",
61 fn adjust_arg_for_abi<'a, 'tcx: 'a>(
62 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
66 match get_pass_mode(fx.tcx, sig.abi, arg.layout().ty, false) {
67 PassMode::NoPass => unimplemented!("pass mode nopass"),
68 PassMode::ByVal(_) => arg.load_value(fx),
69 PassMode::ByRef => arg.force_stack(fx),
73 pub fn cton_sig_from_fn_ty<'a, 'tcx: 'a>(
74 tcx: TyCtxt<'a, 'tcx, 'tcx>,
77 let sig = ty_fn_sig(tcx, fn_ty);
78 assert!(!sig.variadic, "Variadic function are not yet supported");
79 let (call_conv, inputs, output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
80 Abi::Rust => (CallConv::Fast, sig.inputs().to_vec(), sig.output()),
81 Abi::C => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
83 assert_eq!(sig.inputs().len(), 2);
84 let extra_args = match sig.inputs().last().unwrap().sty {
85 ty::Tuple(ref tupled_arguments) => tupled_arguments,
86 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
88 let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
89 inputs.extend(extra_args.into_iter());
90 (CallConv::Fast, inputs, sig.output())
92 Abi::System => bug!("system abi should be selected elsewhere"),
93 Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
94 _ => unimplemented!("unsupported abi {:?}", sig.abi),
99 .filter_map(|ty| match get_pass_mode(tcx, sig.abi, ty, false) {
100 PassMode::ByVal(cton_ty) => Some(cton_ty),
101 PassMode::NoPass => unimplemented!("pass mode nopass"),
102 PassMode::ByRef => Some(pointer_ty(tcx)),
105 let (params, returns) = match get_pass_mode(tcx, sig.abi, output, true) {
106 PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
107 PassMode::ByVal(ret_ty) => (
108 inputs.map(AbiParam::new).collect(),
109 vec![AbiParam::new(ret_ty)],
113 Some(pointer_ty(tcx)) // First param is place to put return val
130 fn ty_fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> ty::FnSig<'tcx> {
131 let sig = match ty.sty {
133 // Shims currently have type TyFnPtr. Not sure this should remain.
134 ty::FnPtr(_) => ty.fn_sig(tcx),
135 ty::Closure(def_id, substs) => {
136 let sig = substs.closure_sig(def_id, tcx);
138 let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
139 sig.map_bound(|sig| tcx.mk_fn_sig(
140 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
147 ty::Generator(def_id, substs, _) => {
148 let sig = substs.poly_sig(def_id, tcx);
150 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
151 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
153 sig.map_bound(|sig| {
154 let state_did = tcx.lang_items().gen_state().unwrap();
155 let state_adt_ref = tcx.adt_def(state_did);
156 let state_substs = tcx.intern_substs(&[
158 sig.return_ty.into(),
160 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
162 tcx.mk_fn_sig(iter::once(env_ty),
165 hir::Unsafety::Normal,
170 _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
172 tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
175 pub fn get_function_name_and_sig<'a, 'tcx>(
176 tcx: TyCtxt<'a, 'tcx, 'tcx>,
177 inst: Instance<'tcx>,
178 ) -> (String, Signature) {
179 assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
180 let fn_ty = inst.ty(tcx);
181 let sig = cton_sig_from_fn_ty(tcx, fn_ty);
182 (tcx.symbol_name(inst).as_str().to_string(), sig)
185 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
186 /// Instance must be monomorphized
187 pub fn get_function_id(&mut self, inst: Instance<'tcx>) -> FuncId {
188 let (name, sig) = get_function_name_and_sig(self.tcx, inst);
190 .declare_function(&name, Linkage::Import, &sig)
194 /// Instance must be monomorphized
195 pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
196 let func_id = self.get_function_id(inst);
198 .declare_func_in_func(func_id, &mut self.bcx.func)
204 input_tys: Vec<types::Type>,
205 output_ty: Option<types::Type>,
208 let sig = Signature {
209 params: input_tys.iter().cloned().map(AbiParam::new).collect(),
211 .map(|output_ty| vec![AbiParam::new(output_ty)])
212 .unwrap_or(Vec::new()),
213 call_conv: CallConv::SystemV,
217 .declare_function(&name, Linkage::Import, &sig)
221 .declare_func_in_func(func_id, &mut self.bcx.func);
222 let call_inst = self.bcx.ins().call(func_ref, args);
223 if output_ty.is_none() {
226 let results = self.bcx.inst_results(call_inst);
227 assert_eq!(results.len(), 1);
234 args: &[CValue<'tcx>],
237 let (input_tys, args): (Vec<_>, Vec<_>) = args
241 self.cton_type(arg.layout().ty).unwrap(),
242 arg.load_value(self),
246 let return_layout = self.layout_of(return_ty);
247 let return_ty = if let ty::Tuple(tup) = return_ty.sty {
249 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
253 Some(self.cton_type(return_ty).unwrap())
255 if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
256 CValue::ByVal(val, return_layout)
258 CValue::ByRef(self.bcx.ins().iconst(self.pointer_type, 0), return_layout)
262 fn self_sig(&self) -> FnSig<'tcx> {
263 ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
266 fn return_type(&self) -> Ty<'tcx> {
267 self.self_sig().output()
271 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
272 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
275 let ssa_analyzed = crate::analyze::analyze(fx);
277 let ret_layout = fx.layout_of(fx.return_type());
278 let output_pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true);
279 let ret_param = match output_pass_mode {
280 PassMode::NoPass => None,
281 PassMode::ByVal(_) => None,
282 PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.pointer_type)),
294 let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
296 // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
297 if Some(local) == fx.mir.spread_arg {
298 // This argument (e.g. the last argument in the "rust-call" ABI)
299 // is a tuple that was spread at the ABI level and now we have
300 // to reconstruct it into a tuple local variable, from multiple
301 // individual function arguments.
303 let tupled_arg_tys = match arg_ty.sty {
304 ty::Tuple(ref tys) => tys,
305 _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
308 let mut ebb_params = Vec::new();
309 for arg_ty in tupled_arg_tys.iter() {
311 get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
312 ebb_params.push(fx.bcx.append_ebb_param(start_ebb, cton_type));
315 (local, ArgKind::Spread(ebb_params), arg_ty)
318 get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
321 ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, cton_type)),
326 .collect::<Vec<(Local, ArgKind, Ty)>>();
328 fx.bcx.switch_to_block(start_ebb);
330 fx.top_nop = Some(fx.bcx.ins().nop());
331 fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
333 for local in fx.mir.args_iter() {
334 let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
335 let pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false);
336 fx.add_global_comment(format!("pass {:?}: {:?} {:?}", local, arg_ty, pass_mode));
339 match output_pass_mode {
340 PassMode::NoPass => {
341 let null = fx.bcx.ins().iconst(fx.pointer_type, 0);
342 //unimplemented!("pass mode nopass");
345 CPlace::Addr(null, None, fx.layout_of(fx.return_type())),
348 PassMode::ByVal(ret_ty) => {
349 fx.bcx.declare_var(mir_var(RETURN_PLACE), ret_ty);
351 .insert(RETURN_PLACE, CPlace::Var(RETURN_PLACE, ret_layout));
356 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
361 for (local, arg_kind, ty) in func_params {
362 let layout = fx.layout_of(ty);
364 if let ArgKind::Normal(ebb_param) = arg_kind {
368 .contains(crate::analyze::Flags::NOT_SSA)
371 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
372 match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false) {
373 PassMode::NoPass => unimplemented!("pass mode nopass"),
374 PassMode::ByVal(_) => fx.bcx.def_var(mir_var(local), ebb_param),
376 let val = CValue::ByRef(ebb_param, fx.layout_of(ty)).load_value(fx);
377 fx.bcx.def_var(mir_var(local), val);
380 fx.local_map.insert(local, CPlace::Var(local, layout));
385 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
386 kind: StackSlotKind::ExplicitSlot,
387 size: layout.size.bytes() as u32,
391 let place = CPlace::from_stack_slot(fx, stack_slot, ty);
394 ArgKind::Normal(ebb_param) => match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false)
396 PassMode::NoPass => unimplemented!("pass mode nopass"),
397 PassMode::ByVal(_) => {
398 place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()))
400 PassMode::ByRef => place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout())),
402 ArgKind::Spread(ebb_params) => {
403 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
404 let sub_place = place.place_field(fx, mir::Field::new(i));
405 match get_pass_mode(fx.tcx, fx.self_sig().abi, sub_place.layout().ty, false) {
406 PassMode::NoPass => unimplemented!("pass mode nopass"),
407 PassMode::ByVal(_) => {
408 sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()))
411 sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()))
417 fx.local_map.insert(local, place);
420 for local in fx.mir.vars_and_temps_iter() {
421 let ty = fx.mir.local_decls[local].ty;
422 let layout = fx.layout_of(ty);
424 let place = if ssa_analyzed
427 .contains(crate::analyze::Flags::NOT_SSA)
429 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
430 kind: StackSlotKind::ExplicitSlot,
431 size: layout.size.bytes() as u32,
434 CPlace::from_stack_slot(fx, stack_slot, ty)
437 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
438 CPlace::Var(local, layout)
441 fx.local_map.insert(local, place);
446 .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
449 pub fn codegen_terminator_call<'a, 'tcx: 'a>(
450 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
451 func: &Operand<'tcx>,
452 args: &[Operand<'tcx>],
453 destination: &Option<(Place<'tcx>, BasicBlock)>,
455 let fn_ty = fx.monomorphize(&func.ty(fx.mir, fx.tcx));
456 let sig = ty_fn_sig(fx.tcx, fn_ty);
458 // Unpack arguments tuple for closures
459 let args = if sig.abi == Abi::RustCall {
460 assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
461 let self_arg = trans_operand(fx, &args[0]);
462 let pack_arg = trans_operand(fx, &args[1]);
463 let mut args = Vec::new();
465 match pack_arg.layout().ty.sty {
466 ty::Tuple(ref tupled_arguments) => {
467 for (i, _) in tupled_arguments.iter().enumerate() {
468 args.push(pack_arg.value_field(fx, mir::Field::new(i)));
471 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
476 .map(|arg| trans_operand(fx, arg))
480 let destination = destination
482 .map(|&(ref place, bb)| (trans_place(fx, place), bb));
484 if let ty::FnDef(def_id, substs) = fn_ty.sty {
485 let sig = ty_fn_sig(fx.tcx, fn_ty);
487 if sig.abi == Abi::RustIntrinsic {
488 crate::intrinsics::codegen_intrinsic_call(fx, def_id, substs, args, destination);
498 destination.map(|(place, _)| place),
501 if let Some((_, dest)) = destination {
502 let ret_ebb = fx.get_ebb(dest);
503 fx.bcx.ins().jump(ret_ebb, &[]);
505 fx.bcx.ins().trap(TrapCode::User(!0));
509 pub fn codegen_call_inner<'a, 'tcx: 'a>(
510 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
511 func: Option<&Operand<'tcx>>,
513 args: Vec<CValue<'tcx>>,
514 ret_place: Option<CPlace<'tcx>>,
516 let sig = ty_fn_sig(fx.tcx, fn_ty);
518 let ret_layout = fx.layout_of(sig.output());
520 let output_pass_mode = get_pass_mode(fx.tcx, sig.abi, sig.output(), true);
521 let return_ptr = match output_pass_mode {
522 PassMode::NoPass => None,
523 PassMode::ByRef => match ret_place {
524 Some(ret_place) => Some(ret_place.expect_addr()),
525 None => Some(fx.bcx.ins().iconst(fx.pointer_type, 0)),
527 PassMode::ByVal(_) => None,
530 let instance = match fn_ty.sty {
531 ty::FnDef(def_id, substs) => {
532 Some(Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap())
537 let func_ref: Option<Value>; // Indirect call target
540 if let Some(Instance {
541 def: InstanceDef::Virtual(_, idx),
545 let (ptr, method) = crate::vtable::get_ptr_and_method_ref(fx, args[0], idx);
546 func_ref = Some(method);
549 func_ref = if instance.is_none() {
550 let func = trans_operand(fx, func.expect("indirect call without func Operand"));
551 Some(func.load_value(fx))
556 args.get(0).map(|arg| adjust_arg_for_abi(fx, sig, *arg))
561 let call_args: Vec<Value> = return_ptr
567 .map(|arg| adjust_arg_for_abi(fx, sig, arg)),
569 .collect::<Vec<_>>();
571 let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, fn_ty));
572 let call_inst = if let Some(func_ref) = func_ref {
573 fx.bcx.ins().call_indirect(sig, func_ref, &call_args)
575 let func_ref = fx.get_function_ref(instance.expect("non-indirect call on non-FnDef type"));
576 fx.bcx.ins().call(func_ref, &call_args)
579 match output_pass_mode {
580 PassMode::NoPass => {}
581 PassMode::ByVal(_) => {
582 if let Some(ret_place) = ret_place {
583 let results = fx.bcx.inst_results(call_inst);
584 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
587 PassMode::ByRef => {}
591 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
592 match get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true) {
593 PassMode::NoPass | PassMode::ByRef => {
594 fx.bcx.ins().return_(&[]);
596 PassMode::ByVal(_) => {
597 let place = fx.get_local_place(RETURN_PLACE);
598 let ret_val = place.to_cvalue(fx).load_value(fx);
599 fx.bcx.ins().return_(&[ret_val]);