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 place = CPlace::new_stack_slot(fx, layout.ty);
345 #[cfg(debug_assertions)]
347 let TyLayout { ty, details } = layout;
348 let ty::layout::LayoutDetails { size, align, abi: _, variants: _, fields: _ } = details;
350 CPlace::Stack(stack_slot, _) => fx.add_entity_comment(stack_slot, format!(
351 "{:?}: {:?} size={} align={},{}",
352 local, ty, size.bytes(), align.abi.bytes(), align.pref.bytes(),
354 CPlace::NoPlace(_) => fx.add_global_comment(format!(
355 "zst {:?}: {:?} size={} align={}, {}",
356 local, ty, size.bytes(), align.abi.bytes(), align.pref.bytes(),
363 // Take stack_addr in advance to avoid many duplicate instructions
364 CPlace::Addr(place.to_addr(fx), None, layout)
367 let prev_place = fx.local_map.insert(local, place);
368 debug_assert!(prev_place.is_none());
372 fn cvalue_for_param<'a, 'tcx: 'a>(
373 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
376 local_field: Option<usize>,
378 ssa_flags: crate::analyze::Flags,
380 let layout = fx.layout_of(arg_ty);
381 let pass_mode = get_pass_mode(fx.tcx, arg_ty, false);
382 let clif_type = pass_mode.get_param_ty(fx);
383 let ebb_param = fx.bcx.append_ebb_param(start_ebb, clif_type);
385 #[cfg(debug_assertions)]
386 add_arg_comment(fx, "arg", local, local_field, Some(ebb_param), pass_mode, ssa_flags, arg_ty);
389 PassMode::NoPass => unimplemented!("pass mode nopass"),
390 PassMode::ByVal(_) => CValue::ByVal(ebb_param, layout),
391 PassMode::ByRef => CValue::ByRef(ebb_param, layout),
395 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
396 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
399 let ssa_analyzed = crate::analyze::analyze(fx);
401 #[cfg(debug_assertions)]
402 fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
404 let ret_layout = fx.layout_of(fx.return_type());
405 let output_pass_mode = get_pass_mode(fx.tcx, fx.return_type(), true);
406 let ret_param = match output_pass_mode {
407 PassMode::NoPass => None,
408 PassMode::ByVal(_) => None,
409 PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.pointer_type)),
412 #[cfg(debug_assertions)]
414 add_local_header_comment(fx);
415 add_arg_comment(fx, "ret", RETURN_PLACE, None, ret_param, output_pass_mode, ssa_analyzed[&RETURN_PLACE], ret_layout.ty);
419 Normal(CValue<'tcx>),
420 Spread(Vec<CValue<'tcx>>),
427 let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
429 // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
430 if Some(local) == fx.mir.spread_arg {
431 // This argument (e.g. the last argument in the "rust-call" ABI)
432 // is a tuple that was spread at the ABI level and now we have
433 // to reconstruct it into a tuple local variable, from multiple
434 // individual function arguments.
436 let tupled_arg_tys = match arg_ty.sty {
437 ty::Tuple(ref tys) => tys,
438 _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
441 let mut params = Vec::new();
442 for (i, arg_ty) in tupled_arg_tys.iter().enumerate() {
443 let param = cvalue_for_param(fx, start_ebb, local, Some(i), arg_ty, ssa_analyzed[&local]);
447 (local, ArgKind::Spread(params), arg_ty)
449 let param = cvalue_for_param(fx, start_ebb, local, None, arg_ty, ssa_analyzed[&local]);
452 ArgKind::Normal(param),
457 .collect::<Vec<(Local, ArgKind, Ty)>>();
459 fx.bcx.switch_to_block(start_ebb);
461 match output_pass_mode {
462 PassMode::NoPass => {
463 fx.local_map.insert(RETURN_PLACE, CPlace::NoPlace(ret_layout));
465 PassMode::ByVal(_) => {
466 let is_ssa = !ssa_analyzed
469 .contains(crate::analyze::Flags::NOT_SSA);
471 local_place(fx, RETURN_PLACE, ret_layout, is_ssa);
476 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
481 for (local, arg_kind, ty) in func_params {
482 let layout = fx.layout_of(ty);
484 let is_ssa = !ssa_analyzed
487 .contains(crate::analyze::Flags::NOT_SSA);
489 let place = local_place(fx, local, layout, is_ssa);
492 ArgKind::Normal(param) => {
493 place.write_cvalue(fx, param);
495 ArgKind::Spread(params) => {
496 for (i, param) in params.into_iter().enumerate() {
497 place.place_field(fx, mir::Field::new(i)).write_cvalue(fx, param);
503 for local in fx.mir.vars_and_temps_iter() {
504 let ty = fx.mir.local_decls[local].ty;
505 let layout = fx.layout_of(ty);
507 let is_ssa = !ssa_analyzed
510 .contains(crate::analyze::Flags::NOT_SSA);
512 local_place(fx, local, layout, is_ssa);
517 .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
520 pub fn codegen_terminator_call<'a, 'tcx: 'a>(
521 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
522 func: &Operand<'tcx>,
523 args: &[Operand<'tcx>],
524 destination: &Option<(Place<'tcx>, BasicBlock)>,
526 let fn_ty = fx.monomorphize(&func.ty(fx.mir, fx.tcx));
527 let sig = ty_fn_sig(fx.tcx, fn_ty);
529 // Unpack arguments tuple for closures
530 let args = if sig.abi == Abi::RustCall {
531 assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
532 let self_arg = trans_operand(fx, &args[0]);
533 let pack_arg = trans_operand(fx, &args[1]);
534 let mut args = Vec::new();
536 match pack_arg.layout().ty.sty {
537 ty::Tuple(ref tupled_arguments) => {
538 for (i, _) in tupled_arguments.iter().enumerate() {
539 args.push(pack_arg.value_field(fx, mir::Field::new(i)));
542 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
547 .map(|arg| trans_operand(fx, arg))
551 let destination = destination
553 .map(|&(ref place, bb)| (trans_place(fx, place), bb));
555 if let ty::FnDef(def_id, substs) = fn_ty.sty {
556 let instance = ty::Instance::resolve(
558 ty::ParamEnv::reveal_all(),
564 InstanceDef::Intrinsic(_) => {
565 crate::intrinsics::codegen_intrinsic_call(fx, def_id, substs, args, destination);
568 InstanceDef::DropGlue(_, None) => {
569 // empty drop glue - a nop.
570 let (_, dest) = destination.expect("Non terminating drop_in_place_real???");
571 let ret_ebb = fx.get_ebb(dest);
572 fx.bcx.ins().jump(ret_ebb, &[]);
584 destination.map(|(place, _)| place),
587 if let Some((_, dest)) = destination {
588 let ret_ebb = fx.get_ebb(dest);
589 fx.bcx.ins().jump(ret_ebb, &[]);
591 trap_unreachable(&mut fx.bcx);
595 pub fn codegen_call_inner<'a, 'tcx: 'a>(
596 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
597 func: Option<&Operand<'tcx>>,
599 args: Vec<CValue<'tcx>>,
600 ret_place: Option<CPlace<'tcx>>,
602 let fn_sig = ty_fn_sig(fx.tcx, fn_ty);
604 let ret_layout = fx.layout_of(fn_sig.output());
606 let output_pass_mode = get_pass_mode(fx.tcx, fn_sig.output(), true);
607 let return_ptr = match output_pass_mode {
608 PassMode::NoPass => None,
609 PassMode::ByRef => match ret_place {
610 Some(ret_place) => Some(ret_place.to_addr(fx)),
611 None => Some(fx.bcx.ins().iconst(fx.pointer_type, 0)),
613 PassMode::ByVal(_) => None,
616 let instance = match fn_ty.sty {
617 ty::FnDef(def_id, substs) => {
618 Some(Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap())
623 let func_ref: Option<Value>; // Indirect call target
626 if let Some(Instance {
627 def: InstanceDef::Virtual(_, idx),
631 let (ptr, method) = crate::vtable::get_ptr_and_method_ref(fx, args[0], idx);
632 func_ref = Some(method);
635 func_ref = if instance.is_none() {
636 let func = trans_operand(fx, func.expect("indirect call without func Operand"));
637 Some(func.load_scalar(fx))
642 args.get(0).map(|arg| adjust_arg_for_abi(fx, *arg))
647 let call_args: Vec<Value> = return_ptr
653 .map(|arg| adjust_arg_for_abi(fx, arg)),
655 .collect::<Vec<_>>();
657 let call_inst = if let Some(func_ref) = func_ref {
658 let sig = fx.bcx.import_signature(clif_sig_from_fn_sig(fx.tcx, fn_sig));
659 fx.bcx.ins().call_indirect(sig, func_ref, &call_args)
661 let func_ref = fx.get_function_ref(instance.expect("non-indirect call on non-FnDef type"));
662 fx.bcx.ins().call(func_ref, &call_args)
665 match output_pass_mode {
666 PassMode::NoPass => {}
667 PassMode::ByVal(_) => {
668 if let Some(ret_place) = ret_place {
669 let results = fx.bcx.inst_results(call_inst);
670 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
673 PassMode::ByRef => {}
677 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
678 match get_pass_mode(fx.tcx, fx.return_type(), true) {
679 PassMode::NoPass | PassMode::ByRef => {
680 fx.bcx.ins().return_(&[]);
682 PassMode::ByVal(_) => {
683 let place = fx.get_local_place(RETURN_PLACE);
684 let ret_val = place.to_cvalue(fx).load_scalar(fx);
685 fx.bcx.ins().return_(&[ret_val]);