5 use rustc::ty::layout::{Scalar, Primitive, Integer, FloatTy};
6 use rustc_target::spec::abi::Abi;
10 #[derive(Copy, Clone, Debug)]
18 fn get_param_ty(self, fx: &FunctionCx<impl Backend>) -> Type {
20 PassMode::NoPass => unimplemented!("pass mode nopass"),
21 PassMode::ByVal(clif_type) => clif_type,
22 PassMode::ByRef => fx.pointer_type,
27 pub fn scalar_to_clif_type(tcx: TyCtxt, scalar: Scalar) -> Type {
29 Primitive::Int(int, _sign) => match int {
30 Integer::I8 => types::I8,
31 Integer::I16 => types::I16,
32 Integer::I32 => types::I32,
33 Integer::I64 => types::I64,
34 Integer::I128 => unimpl!("u/i128"),
36 Primitive::Float(flt) => match flt {
37 FloatTy::F32 => types::F32,
38 FloatTy::F64 => types::F64,
40 Primitive::Pointer => pointer_ty(tcx),
44 fn get_pass_mode<'a, 'tcx: 'a>(
45 tcx: TyCtxt<'a, 'tcx, 'tcx>,
50 .layout_of(ParamEnv::reveal_all().and(ty))
52 assert!(!layout.is_unsized());
54 if layout.size.bytes() == 0 {
62 layout::Abi::Uninhabited => {
69 layout::Abi::Scalar(scalar) => PassMode::ByVal(scalar_to_clif_type(tcx, scalar.clone())),
71 // FIXME implement ScalarPair and Vector Abi in a cg_llvm compatible way
72 layout::Abi::ScalarPair(_, _) => PassMode::ByRef,
73 layout::Abi::Vector { .. } => PassMode::ByRef,
75 layout::Abi::Aggregate { .. } => PassMode::ByRef,
80 fn adjust_arg_for_abi<'a, 'tcx: 'a>(
81 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
84 match get_pass_mode(fx.tcx, arg.layout().ty, false) {
85 PassMode::NoPass => unimplemented!("pass mode nopass"),
86 PassMode::ByVal(_) => arg.load_scalar(fx),
87 PassMode::ByRef => arg.force_stack(fx),
91 fn clif_sig_from_fn_sig<'a, 'tcx: 'a>(
92 tcx: TyCtxt<'a, 'tcx, 'tcx>,
95 let (call_conv, inputs, output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
96 Abi::Rust => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
97 Abi::C => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
99 assert_eq!(sig.inputs().len(), 2);
100 let extra_args = match sig.inputs().last().unwrap().sty {
101 ty::Tuple(ref tupled_arguments) => tupled_arguments,
102 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
104 let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
105 inputs.extend(extra_args.into_iter());
106 (CallConv::SystemV, inputs, sig.output())
108 Abi::System => bug!("system abi should be selected elsewhere"),
109 Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
110 _ => unimplemented!("unsupported abi {:?}", sig.abi),
115 .filter_map(|ty| match get_pass_mode(tcx, ty, false) {
116 PassMode::ByVal(clif_ty) => Some(clif_ty),
117 PassMode::NoPass => unimplemented!("pass mode nopass"),
118 PassMode::ByRef => Some(pointer_ty(tcx)),
121 let (params, returns) = match get_pass_mode(tcx, output, true) {
122 PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
123 PassMode::ByVal(ret_ty) => (
124 inputs.map(AbiParam::new).collect(),
125 vec![AbiParam::new(ret_ty)],
129 Some(pointer_ty(tcx)) // First param is place to put return val
146 pub fn ty_fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> ty::FnSig<'tcx> {
147 let sig = match ty.sty {
149 // Shims currently have type TyFnPtr. Not sure this should remain.
150 ty::FnPtr(_) => ty.fn_sig(tcx),
151 ty::Closure(def_id, substs) => {
152 let sig = substs.closure_sig(def_id, tcx);
154 let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
155 sig.map_bound(|sig| tcx.mk_fn_sig(
156 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
163 ty::Generator(def_id, substs, _) => {
164 let sig = substs.poly_sig(def_id, tcx);
166 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
167 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
169 sig.map_bound(|sig| {
170 let state_did = tcx.lang_items().gen_state().unwrap();
171 let state_adt_ref = tcx.adt_def(state_did);
172 let state_substs = tcx.intern_substs(&[
174 sig.return_ty.into(),
176 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
178 tcx.mk_fn_sig(iter::once(env_ty),
181 hir::Unsafety::Normal,
186 _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
188 tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
191 pub fn get_function_name_and_sig<'a, 'tcx>(
192 tcx: TyCtxt<'a, 'tcx, 'tcx>,
193 inst: Instance<'tcx>,
194 ) -> (String, Signature) {
195 assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
196 let fn_ty = inst.ty(tcx);
197 let fn_sig = ty_fn_sig(tcx, fn_ty);
199 unimpl!("Variadic functions are not yet supported");
201 let sig = clif_sig_from_fn_sig(tcx, fn_sig);
202 (tcx.symbol_name(inst).as_str().to_string(), sig)
205 /// Instance must be monomorphized
206 pub fn import_function<'a, 'tcx: 'a>(
207 tcx: TyCtxt<'a, 'tcx, 'tcx>,
208 module: &mut Module<impl Backend>,
209 inst: Instance<'tcx>,
211 let (name, sig) = get_function_name_and_sig(tcx, inst);
213 .declare_function(&name, Linkage::Import, &sig)
217 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
218 /// Instance must be monomorphized
219 pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
220 let func_id = import_function(self.tcx, self.module, inst);
221 let func_ref = self.module
222 .declare_func_in_func(func_id, &mut self.bcx.func);
224 #[cfg(debug_assertions)]
225 self.add_entity_comment(func_ref, format!("{:?}", inst));
233 input_tys: Vec<types::Type>,
234 output_ty: Option<types::Type>,
237 let sig = Signature {
238 params: input_tys.iter().cloned().map(AbiParam::new).collect(),
240 .map(|output_ty| vec![AbiParam::new(output_ty)])
241 .unwrap_or(Vec::new()),
242 call_conv: CallConv::SystemV,
246 .declare_function(&name, Linkage::Import, &sig)
250 .declare_func_in_func(func_id, &mut self.bcx.func);
251 let call_inst = self.bcx.ins().call(func_ref, args);
252 if output_ty.is_none() {
255 let results = self.bcx.inst_results(call_inst);
256 assert_eq!(results.len(), 1);
263 args: &[CValue<'tcx>],
266 let (input_tys, args): (Vec<_>, Vec<_>) = args
270 self.clif_type(arg.layout().ty).unwrap(),
271 arg.load_scalar(self),
275 let return_layout = self.layout_of(return_ty);
276 let return_ty = if let ty::Tuple(tup) = return_ty.sty {
278 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
282 Some(self.clif_type(return_ty).unwrap())
284 if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
285 CValue::ByVal(val, return_layout)
287 CValue::ByRef(self.bcx.ins().iconst(self.pointer_type, 0), return_layout)
291 fn self_sig(&self) -> FnSig<'tcx> {
292 ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
295 fn return_type(&self) -> Ty<'tcx> {
296 self.self_sig().output()
300 #[cfg(debug_assertions)]
301 fn add_arg_comment<'a, 'tcx: 'a>(
302 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
305 local_field: Option<usize>,
306 param: Option<Value>,
308 ssa: crate::analyze::Flags,
311 let local_field = if let Some(local_field) = local_field {
312 Cow::Owned(format!(".{}", local_field))
316 let param = if let Some(param) = param {
317 Cow::Owned(format!("= {:?}", param))
321 let pass_mode = format!("{:?}", pass_mode);
322 fx.add_global_comment(format!(
323 "{msg:5} {local:>3}{local_field:<5} {param:10} {pass_mode:20} {ssa:10} {ty:?}",
324 msg=msg, local=format!("{:?}", local), local_field=local_field, param=param, pass_mode=pass_mode, ssa=format!("{:?}", ssa), ty=ty,
328 #[cfg(debug_assertions)]
329 fn add_local_header_comment(fx: &mut FunctionCx<impl Backend>) {
330 fx.add_global_comment(format!("msg loc.idx param pass mode ssa flags ty"));
333 fn local_place<'a, 'tcx: 'a>(
334 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
336 layout: TyLayout<'tcx>,
339 let place = if is_ssa {
340 fx.bcx.declare_var(mir_var(local), fx.clif_type(layout.ty).unwrap());
341 CPlace::Var(local, layout)
343 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
344 kind: StackSlotKind::ExplicitSlot,
345 size: layout.size.bytes() as u32,
349 #[cfg(debug_assertions)]
351 let TyLayout { ty, details } = layout;
352 let ty::layout::LayoutDetails { size, align, abi: _, variants: _, fields: _ } = details;
353 fx.add_entity_comment(stack_slot, format!(
354 "{:?}: {:?} size={} align={},{}",
355 local, ty, size.bytes(), align.abi.bytes(), align.pref.bytes(),
359 CPlace::from_stack_slot(fx, stack_slot, layout.ty)
362 let prev_place = fx.local_map.insert(local, place);
363 debug_assert!(prev_place.is_none());
367 fn cvalue_for_param<'a, 'tcx: 'a>(
368 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
371 local_field: Option<usize>,
373 ssa_flags: crate::analyze::Flags,
375 let layout = fx.layout_of(arg_ty);
376 let pass_mode = get_pass_mode(fx.tcx, arg_ty, false);
377 let clif_type = pass_mode.get_param_ty(fx);
378 let ebb_param = fx.bcx.append_ebb_param(start_ebb, clif_type);
380 #[cfg(debug_assertions)]
381 add_arg_comment(fx, "arg", local, local_field, Some(ebb_param), pass_mode, ssa_flags, arg_ty);
384 PassMode::NoPass => unimplemented!("pass mode nopass"),
385 PassMode::ByVal(_) => CValue::ByVal(ebb_param, layout),
386 PassMode::ByRef => CValue::ByRef(ebb_param, layout),
390 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
391 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
394 let ssa_analyzed = crate::analyze::analyze(fx);
396 #[cfg(debug_assertions)]
397 fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
399 let ret_layout = fx.layout_of(fx.return_type());
400 let output_pass_mode = get_pass_mode(fx.tcx, fx.return_type(), true);
401 let ret_param = match output_pass_mode {
402 PassMode::NoPass => None,
403 PassMode::ByVal(_) => None,
404 PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.pointer_type)),
407 #[cfg(debug_assertions)]
409 add_local_header_comment(fx);
410 add_arg_comment(fx, "ret", RETURN_PLACE, None, ret_param, output_pass_mode, ssa_analyzed[&RETURN_PLACE], ret_layout.ty);
414 Normal(CValue<'tcx>),
415 Spread(Vec<CValue<'tcx>>),
422 let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
424 // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
425 if Some(local) == fx.mir.spread_arg {
426 // This argument (e.g. the last argument in the "rust-call" ABI)
427 // is a tuple that was spread at the ABI level and now we have
428 // to reconstruct it into a tuple local variable, from multiple
429 // individual function arguments.
431 let tupled_arg_tys = match arg_ty.sty {
432 ty::Tuple(ref tys) => tys,
433 _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
436 let mut params = Vec::new();
437 for (i, arg_ty) in tupled_arg_tys.iter().enumerate() {
438 let param = cvalue_for_param(fx, start_ebb, local, Some(i), arg_ty, ssa_analyzed[&local]);
442 (local, ArgKind::Spread(params), arg_ty)
444 let param = cvalue_for_param(fx, start_ebb, local, None, arg_ty, ssa_analyzed[&local]);
447 ArgKind::Normal(param),
452 .collect::<Vec<(Local, ArgKind, Ty)>>();
454 fx.bcx.switch_to_block(start_ebb);
456 match output_pass_mode {
457 PassMode::NoPass => {
458 let null = fx.bcx.ins().iconst(fx.pointer_type, 0);
461 CPlace::Addr(null, None, ret_layout),
464 PassMode::ByVal(_) => {
465 let is_ssa = !ssa_analyzed
468 .contains(crate::analyze::Flags::NOT_SSA);
470 local_place(fx, RETURN_PLACE, ret_layout, is_ssa);
475 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
480 for (local, arg_kind, ty) in func_params {
481 let layout = fx.layout_of(ty);
483 let is_ssa = !ssa_analyzed
486 .contains(crate::analyze::Flags::NOT_SSA);
488 let place = local_place(fx, local, layout, is_ssa);
491 ArgKind::Normal(param) => {
492 place.write_cvalue(fx, param);
494 ArgKind::Spread(params) => {
495 for (i, param) in params.into_iter().enumerate() {
496 place.place_field(fx, mir::Field::new(i)).write_cvalue(fx, param);
502 for local in fx.mir.vars_and_temps_iter() {
503 let ty = fx.mir.local_decls[local].ty;
504 let layout = fx.layout_of(ty);
506 let is_ssa = !ssa_analyzed
509 .contains(crate::analyze::Flags::NOT_SSA);
511 local_place(fx, local, layout, is_ssa);
516 .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
519 pub fn codegen_terminator_call<'a, 'tcx: 'a>(
520 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
521 func: &Operand<'tcx>,
522 args: &[Operand<'tcx>],
523 destination: &Option<(Place<'tcx>, BasicBlock)>,
525 let fn_ty = fx.monomorphize(&func.ty(fx.mir, fx.tcx));
526 let sig = ty_fn_sig(fx.tcx, fn_ty);
528 // Unpack arguments tuple for closures
529 let args = if sig.abi == Abi::RustCall {
530 assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
531 let self_arg = trans_operand(fx, &args[0]);
532 let pack_arg = trans_operand(fx, &args[1]);
533 let mut args = Vec::new();
535 match pack_arg.layout().ty.sty {
536 ty::Tuple(ref tupled_arguments) => {
537 for (i, _) in tupled_arguments.iter().enumerate() {
538 args.push(pack_arg.value_field(fx, mir::Field::new(i)));
541 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
546 .map(|arg| trans_operand(fx, arg))
550 let destination = destination
552 .map(|&(ref place, bb)| (trans_place(fx, place), bb));
554 if let ty::FnDef(def_id, substs) = fn_ty.sty {
555 let instance = ty::Instance::resolve(
557 ty::ParamEnv::reveal_all(),
563 InstanceDef::Intrinsic(_) => {
564 crate::intrinsics::codegen_intrinsic_call(fx, def_id, substs, args, destination);
567 InstanceDef::DropGlue(_, None) => {
568 // empty drop glue - a nop.
569 let (_, dest) = destination.expect("Non terminating drop_in_place_real???");
570 let ret_ebb = fx.get_ebb(dest);
571 fx.bcx.ins().jump(ret_ebb, &[]);
583 destination.map(|(place, _)| place),
586 if let Some((_, dest)) = destination {
587 let ret_ebb = fx.get_ebb(dest);
588 fx.bcx.ins().jump(ret_ebb, &[]);
590 trap_unreachable(&mut fx.bcx);
594 pub fn codegen_call_inner<'a, 'tcx: 'a>(
595 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
596 func: Option<&Operand<'tcx>>,
598 args: Vec<CValue<'tcx>>,
599 ret_place: Option<CPlace<'tcx>>,
601 let fn_sig = ty_fn_sig(fx.tcx, fn_ty);
603 let ret_layout = fx.layout_of(fn_sig.output());
605 let output_pass_mode = get_pass_mode(fx.tcx, fn_sig.output(), true);
606 let return_ptr = match output_pass_mode {
607 PassMode::NoPass => None,
608 PassMode::ByRef => match ret_place {
609 Some(ret_place) => Some(ret_place.expect_addr()),
610 None => Some(fx.bcx.ins().iconst(fx.pointer_type, 0)),
612 PassMode::ByVal(_) => None,
615 let instance = match fn_ty.sty {
616 ty::FnDef(def_id, substs) => {
617 Some(Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap())
622 let func_ref: Option<Value>; // Indirect call target
625 if let Some(Instance {
626 def: InstanceDef::Virtual(_, idx),
630 let (ptr, method) = crate::vtable::get_ptr_and_method_ref(fx, args[0], idx);
631 func_ref = Some(method);
634 func_ref = if instance.is_none() {
635 let func = trans_operand(fx, func.expect("indirect call without func Operand"));
636 Some(func.load_scalar(fx))
641 args.get(0).map(|arg| adjust_arg_for_abi(fx, *arg))
646 let call_args: Vec<Value> = return_ptr
652 .map(|arg| adjust_arg_for_abi(fx, arg)),
654 .collect::<Vec<_>>();
656 let call_inst = if let Some(func_ref) = func_ref {
657 let sig = fx.bcx.import_signature(clif_sig_from_fn_sig(fx.tcx, fn_sig));
658 fx.bcx.ins().call_indirect(sig, func_ref, &call_args)
660 let func_ref = fx.get_function_ref(instance.expect("non-indirect call on non-FnDef type"));
661 fx.bcx.ins().call(func_ref, &call_args)
664 match output_pass_mode {
665 PassMode::NoPass => {}
666 PassMode::ByVal(_) => {
667 if let Some(ret_place) = ret_place {
668 let results = fx.bcx.inst_results(call_inst);
669 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
672 PassMode::ByRef => {}
676 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
677 match get_pass_mode(fx.tcx, fx.return_type(), true) {
678 PassMode::NoPass | PassMode::ByRef => {
679 fx.bcx.ins().return_(&[]);
681 PassMode::ByVal(_) => {
682 let place = fx.get_local_place(RETURN_PLACE);
683 let ret_val = place.to_cvalue(fx).load_scalar(fx);
684 fx.bcx.ins().return_(&[ret_val]);