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.module.pointer_type(),
25 fn get_pass_mode<'a, 'tcx: 'a>(
26 tcx: TyCtxt<'a, 'tcx, 'tcx>,
32 !tcx.layout_of(ParamEnv::reveal_all().and(ty))
36 if ty.sty == tcx.mk_nil().sty {
43 } else if let Some(ret_ty) = crate::common::cton_type_from_ty(tcx, ty) {
44 PassMode::ByVal(ret_ty)
47 unimplemented!("Non scalars are not yet supported for \"C\" abi");
53 pub fn cton_sig_from_fn_ty<'a, 'tcx: 'a>(
54 tcx: TyCtxt<'a, 'tcx, 'tcx>,
57 let sig = ty_fn_sig(tcx, fn_ty);
58 assert!(!sig.variadic, "Variadic function are not yet supported");
59 let (call_conv, inputs, output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
60 Abi::Rust => (CallConv::Fast, sig.inputs().to_vec(), sig.output()),
61 Abi::C => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
63 assert_eq!(sig.inputs().len(), 2);
64 let extra_args = match sig.inputs().last().unwrap().sty {
65 ty::Tuple(ref tupled_arguments) => tupled_arguments,
66 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
68 let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
69 inputs.extend(extra_args.into_iter());
70 (CallConv::Fast, inputs, sig.output())
72 Abi::System => bug!("system abi should be selected elsewhere"),
73 Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
74 _ => unimplemented!("unsupported abi {:?}", sig.abi),
79 .filter_map(|ty| match get_pass_mode(tcx, sig.abi, ty, false) {
80 PassMode::ByVal(cton_ty) => Some(cton_ty),
81 PassMode::NoPass => unimplemented!("pass mode nopass"),
82 PassMode::ByRef => Some(pointer_ty(tcx)),
85 let (params, returns) = match get_pass_mode(tcx, sig.abi, output, true) {
86 PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
87 PassMode::ByVal(ret_ty) => (
88 inputs.map(AbiParam::new).collect(),
89 vec![AbiParam::new(ret_ty)],
93 Some(pointer_ty(tcx)).into_iter() // First param is place to put return val
106 argument_bytes: None,
110 fn ty_fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> ty::FnSig<'tcx> {
111 let sig = match ty.sty {
113 // Shims currently have type TyFnPtr. Not sure this should remain.
114 ty::FnPtr(_) => ty.fn_sig(tcx),
115 ty::Closure(def_id, substs) => {
116 let sig = substs.closure_sig(def_id, tcx);
118 let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
119 sig.map_bound(|sig| tcx.mk_fn_sig(
120 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
127 ty::Generator(def_id, substs, _) => {
128 let sig = substs.poly_sig(def_id, tcx);
130 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
131 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
133 sig.map_bound(|sig| {
134 let state_did = tcx.lang_items().gen_state().unwrap();
135 let state_adt_ref = tcx.adt_def(state_did);
136 let state_substs = tcx.intern_substs(&[
138 sig.return_ty.into(),
140 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
142 tcx.mk_fn_sig(iter::once(env_ty),
145 hir::Unsafety::Normal,
150 _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
152 tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
155 pub fn get_function_name_and_sig<'a, 'tcx>(
156 tcx: TyCtxt<'a, 'tcx, 'tcx>,
157 inst: Instance<'tcx>,
158 ) -> (String, Signature) {
159 assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
160 let fn_ty = inst.ty(tcx);
161 let sig = cton_sig_from_fn_ty(tcx, fn_ty);
162 (tcx.symbol_name(inst).as_str().to_string(), sig)
165 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
166 /// Instance must be monomorphized
167 pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
168 let (name, sig) = get_function_name_and_sig(self.tcx, inst);
171 .declare_function(&name, Linkage::Import, &sig)
174 .declare_func_in_func(func_id, &mut self.bcx.func)
180 input_tys: Vec<types::Type>,
181 output_ty: Option<types::Type>,
184 let sig = Signature {
185 params: input_tys.iter().cloned().map(AbiParam::new).collect(),
186 returns: vec![AbiParam::new(output_ty.unwrap_or(types::VOID))],
187 call_conv: CallConv::SystemV,
188 argument_bytes: None,
192 .declare_function(&name, Linkage::Import, &sig)
196 .declare_func_in_func(func_id, &mut self.bcx.func);
197 let call_inst = self.bcx.ins().call(func_ref, args);
198 if output_ty.is_none() {
201 let results = self.bcx.inst_results(call_inst);
202 assert_eq!(results.len(), 1);
209 args: &[CValue<'tcx>],
212 let (input_tys, args): (Vec<_>, Vec<_>) = args
216 self.cton_type(arg.layout().ty).unwrap(),
217 arg.load_value(self),
220 let return_layout = self.layout_of(return_ty);
221 let return_ty = if let ty::Tuple(tup) = return_ty.sty {
223 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
227 Some(self.cton_type(return_ty).unwrap())
229 if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
230 CValue::ByVal(val, return_layout)
233 self.bcx.ins().iconst(self.module.pointer_type(), 0),
239 fn self_sig(&self) -> FnSig<'tcx> {
240 ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
243 fn return_type(&self) -> Ty<'tcx> {
244 self.self_sig().output()
248 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
249 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
252 let ssa_analyzed = crate::analyze::analyze(fx);
254 match fx.self_sig().abi {
255 Abi::Rust | Abi::RustCall => {}
256 _ => unimplemented!("declared function with non \"rust\" or \"rust-call\" abi"),
259 let ret_layout = fx.layout_of(fx.return_type());
260 let output_pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true);
261 let ret_param = match output_pass_mode {
262 PassMode::NoPass => None,
263 PassMode::ByVal(_) => None,
264 PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.module.pointer_type())),
276 let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
278 // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
279 if Some(local) == fx.mir.spread_arg {
280 // This argument (e.g. the last argument in the "rust-call" ABI)
281 // is a tuple that was spread at the ABI level and now we have
282 // to reconstruct it into a tuple local variable, from multiple
283 // individual function arguments.
285 let tupled_arg_tys = match arg_ty.sty {
286 ty::Tuple(ref tys) => tys,
287 _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
290 let mut ebb_params = Vec::new();
291 for arg_ty in tupled_arg_tys.iter() {
293 get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
294 ebb_params.push(fx.bcx.append_ebb_param(start_ebb, cton_type));
297 (local, ArgKind::Spread(ebb_params), arg_ty)
300 get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
303 ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, cton_type)),
307 }).collect::<Vec<(Local, ArgKind, Ty)>>();
309 fx.bcx.switch_to_block(start_ebb);
311 fx.top_nop = Some(fx.bcx.ins().nop());
312 fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
314 match output_pass_mode {
315 PassMode::NoPass => {
316 let null = fx.bcx.ins().iconst(fx.module.pointer_type(), 0);
317 //unimplemented!("pass mode nopass");
320 CPlace::Addr(null, None, fx.layout_of(fx.return_type())),
323 PassMode::ByVal(ret_ty) => {
324 fx.bcx.declare_var(mir_var(RETURN_PLACE), ret_ty);
326 .insert(RETURN_PLACE, CPlace::Var(RETURN_PLACE, ret_layout));
331 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
336 for (local, arg_kind, ty) in func_params {
337 let layout = fx.layout_of(ty);
339 if let ArgKind::Normal(ebb_param) = arg_kind {
343 .contains(crate::analyze::Flags::NOT_SSA)
346 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
347 match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false) {
348 PassMode::NoPass => unimplemented!("pass mode nopass"),
349 PassMode::ByVal(_) => fx.bcx.def_var(mir_var(local), ebb_param),
351 let val = CValue::ByRef(ebb_param, fx.layout_of(ty)).load_value(fx);
352 fx.bcx.def_var(mir_var(local), val);
355 fx.local_map.insert(local, CPlace::Var(local, layout));
360 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
361 kind: StackSlotKind::ExplicitSlot,
362 size: layout.size.bytes() as u32,
366 let place = CPlace::from_stack_slot(fx, stack_slot, ty);
369 ArgKind::Normal(ebb_param) => match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false)
371 PassMode::NoPass => unimplemented!("pass mode nopass"),
372 PassMode::ByVal(_) => {
373 place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()))
375 PassMode::ByRef => place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout())),
377 ArgKind::Spread(ebb_params) => {
378 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
379 let sub_place = place.place_field(fx, mir::Field::new(i));
380 match get_pass_mode(fx.tcx, fx.self_sig().abi, sub_place.layout().ty, false) {
381 PassMode::NoPass => unimplemented!("pass mode nopass"),
382 PassMode::ByVal(_) => {
383 sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()))
386 sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()))
392 fx.local_map.insert(local, place);
395 for local in fx.mir.vars_and_temps_iter() {
396 let ty = fx.mir.local_decls[local].ty;
397 let layout = fx.layout_of(ty);
399 let place = if ssa_analyzed
402 .contains(crate::analyze::Flags::NOT_SSA)
404 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
405 kind: StackSlotKind::ExplicitSlot,
406 size: layout.size.bytes() as u32,
409 CPlace::from_stack_slot(fx, stack_slot, ty)
412 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
413 CPlace::Var(local, layout)
416 fx.local_map.insert(local, place);
421 .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
424 pub fn codegen_call<'a, 'tcx: 'a>(
425 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
426 func: &Operand<'tcx>,
427 args: &[Operand<'tcx>],
428 destination: &Option<(Place<'tcx>, BasicBlock)>,
430 let fn_ty = fx.monomorphize(&func.ty(&fx.mir.local_decls, fx.tcx));
431 let sig = ty_fn_sig(fx.tcx, fn_ty);
433 // Unpack arguments tuple for closures
434 let args = if sig.abi == Abi::RustCall {
435 assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
436 let self_arg = trans_operand(fx, &args[0]);
437 let pack_arg = trans_operand(fx, &args[1]);
438 let mut args = Vec::new();
440 match pack_arg.layout().ty.sty {
441 ty::Tuple(ref tupled_arguments) => {
442 for (i, _) in tupled_arguments.iter().enumerate() {
443 args.push(pack_arg.value_field(fx, mir::Field::new(i)));
446 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
451 .map(|arg| trans_operand(fx, arg))
455 let destination = destination
457 .map(|(place, bb)| (trans_place(fx, place), *bb));
459 if codegen_intrinsic_call(fx, fn_ty, sig, &args, destination) {
463 let ret_layout = fx.layout_of(sig.output());
465 let output_pass_mode = get_pass_mode(fx.tcx, sig.abi, sig.output(), true);
466 let return_ptr = match output_pass_mode {
467 PassMode::NoPass => None,
468 PassMode::ByRef => match destination {
469 Some((place, _)) => Some(place.expect_addr()),
470 None => Some(fx.bcx.ins().iconst(fx.module.pointer_type(), 0)),
472 PassMode::ByVal(_) => None,
475 let call_args: Vec<Value> = return_ptr
477 .chain(args.into_iter().map(|arg| {
478 match get_pass_mode(fx.tcx, sig.abi, arg.layout().ty, false) {
479 PassMode::NoPass => unimplemented!("pass mode nopass"),
480 PassMode::ByVal(_) => arg.load_value(fx),
481 PassMode::ByRef => arg.force_stack(fx),
483 })).collect::<Vec<_>>();
485 let call_inst = match fn_ty.sty {
486 ty::FnDef(def_id, substs) => {
487 let func_ref = fx.get_function_ref(
488 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap(),
490 fx.bcx.ins().call(func_ref, &call_args)
493 let func = trans_operand(fx, func);
494 let func = func.load_value(fx);
495 let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, fn_ty));
496 fx.bcx.ins().call_indirect(sig, func, &call_args)
500 match output_pass_mode {
501 PassMode::NoPass => {}
502 PassMode::ByVal(_) => {
503 if let Some((ret_place, _)) = destination {
504 let results = fx.bcx.inst_results(call_inst);
505 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
508 PassMode::ByRef => {}
510 if let Some((_, dest)) = destination {
511 let ret_ebb = fx.get_ebb(dest);
512 fx.bcx.ins().jump(ret_ebb, &[]);
514 fx.bcx.ins().trap(TrapCode::User(!0));
518 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
519 match get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true) {
520 PassMode::NoPass | PassMode::ByRef => {
521 fx.bcx.ins().return_(&[]);
523 PassMode::ByVal(_) => {
524 let place = fx.get_local_place(RETURN_PLACE);
525 let ret_val = place.to_cvalue(fx).load_value(fx);
526 fx.bcx.ins().return_(&[ret_val]);
531 fn codegen_intrinsic_call<'a, 'tcx: 'a>(
532 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
535 args: &[CValue<'tcx>],
536 destination: Option<(CPlace<'tcx>, BasicBlock)>,
538 if let ty::FnDef(def_id, substs) = fn_ty.sty {
539 if sig.abi == Abi::RustIntrinsic {
540 let intrinsic = fx.tcx.item_name(def_id).as_str();
541 let intrinsic = &intrinsic[..];
543 let ret = match destination {
544 Some((place, _)) => place,
546 // Insert non returning intrinsics here
549 fx.bcx.ins().trap(TrapCode::User(!0 - 1));
552 fx.bcx.ins().trap(TrapCode::User(!0 - 1));
554 _ => unimplemented!("unsupported instrinsic {}", intrinsic),
560 let nil_ty = fx.tcx.mk_nil();
561 let u64_layout = fx.layout_of(fx.tcx.types.u64);
562 let usize_layout = fx.layout_of(fx.tcx.types.usize);
566 assert_eq!(args.len(), 1);
569 assert_eq!(args.len(), 2);
570 let base = args[0].load_value(fx);
571 let offset = args[1].load_value(fx);
572 let res = fx.bcx.ins().iadd(base, offset);
573 let res = CValue::ByVal(res, ret.layout());
574 ret.write_cvalue(fx, res);
576 "likely" | "unlikely" => {
577 assert_eq!(args.len(), 1);
578 ret.write_cvalue(fx, args[0]);
580 "copy" | "copy_nonoverlapping" => {
581 let elem_ty = substs.type_at(0);
582 let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
586 .iconst(fx.module.pointer_type(), elem_size as i64);
587 assert_eq!(args.len(), 3);
590 let count = args[2].load_value(fx);
591 let byte_amount = fx.bcx.ins().imul(count, elem_size);
594 &[dst, src, CValue::ByVal(byte_amount, usize_layout)],
598 "discriminant_value" => {
599 assert_eq!(args.len(), 1);
600 let discr = crate::base::trans_get_discriminant(fx, args[0], ret.layout());
601 ret.write_cvalue(fx, discr);
604 assert_eq!(args.len(), 0);
605 let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
606 let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
607 ret.write_cvalue(fx, size_of);
610 assert_eq!(args.len(), 0);
611 let type_id = fx.tcx.type_id_hash(substs.type_at(0));
612 let type_id = CValue::const_val(fx, u64_layout.ty, type_id as i64);
613 ret.write_cvalue(fx, type_id);
616 assert_eq!(args.len(), 0);
617 let min_align = fx.layout_of(substs.type_at(0)).align.abi();
618 let min_align = CValue::const_val(fx, usize_layout.ty, min_align as i64);
619 ret.write_cvalue(fx, min_align);
621 _ if intrinsic.starts_with("unchecked_") => {
622 assert_eq!(args.len(), 2);
623 let bin_op = match intrinsic {
624 "unchecked_div" => BinOp::Div,
625 "unchecked_rem" => BinOp::Rem,
626 "unchecked_shl" => BinOp::Shl,
627 "unchecked_shr" => BinOp::Shr,
628 _ => unimplemented!("intrinsic {}", intrinsic),
630 let res = match ret.layout().ty.sty {
631 ty::Uint(_) => crate::base::trans_int_binop(
639 ty::Int(_) => crate::base::trans_int_binop(
649 ret.write_cvalue(fx, res);
651 _ if intrinsic.ends_with("_with_overflow") => {
652 assert_eq!(args.len(), 2);
653 assert_eq!(args[0].layout().ty, args[1].layout().ty);
654 let bin_op = match intrinsic {
655 "add_with_overflow" => BinOp::Add,
656 "sub_with_overflow" => BinOp::Sub,
657 "mul_with_overflow" => BinOp::Mul,
658 _ => unimplemented!("intrinsic {}", intrinsic),
660 let res = match args[0].layout().ty.sty {
661 ty::Uint(_) => crate::base::trans_checked_int_binop(
669 ty::Int(_) => crate::base::trans_checked_int_binop(
679 ret.write_cvalue(fx, res);
681 _ if intrinsic.starts_with("overflowing_") => {
682 assert_eq!(args.len(), 2);
683 assert_eq!(args[0].layout().ty, args[1].layout().ty);
684 let bin_op = match intrinsic {
685 "overflowing_add" => BinOp::Add,
686 "overflowing_sub" => BinOp::Sub,
687 "overflowing_mul" => BinOp::Mul,
688 _ => unimplemented!("intrinsic {}", intrinsic),
690 let res = match args[0].layout().ty.sty {
691 ty::Uint(_) => crate::base::trans_int_binop(
699 ty::Int(_) => crate::base::trans_int_binop(
709 ret.write_cvalue(fx, res);
712 assert_eq!(args.len(), 2);
713 let base = args[0].load_value(fx);
714 let offset = args[1].load_value(fx);
715 let res = fx.bcx.ins().iadd(base, offset);
716 ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
719 assert_eq!(args.len(), 1);
720 let src_ty = substs.type_at(0);
721 let dst_ty = substs.type_at(1);
722 assert_eq!(args[0].layout().ty, src_ty);
723 let addr = args[0].force_stack(fx);
724 let dst_layout = fx.layout_of(dst_ty);
725 ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
728 assert_eq!(args.len(), 0);
729 let ty = substs.type_at(0);
730 let layout = fx.layout_of(ty);
731 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
732 kind: StackSlotKind::ExplicitSlot,
733 size: layout.size.bytes() as u32,
737 let uninit_place = CPlace::from_stack_slot(fx, stack_slot, ty);
738 let uninit_val = uninit_place.to_cvalue(fx);
739 ret.write_cvalue(fx, uninit_val);
741 "ctlz" | "ctlz_nonzero" => {
742 assert_eq!(args.len(), 1);
743 let arg = args[0].load_value(fx);
744 let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
745 ret.write_cvalue(fx, res);
747 "cttz" | "cttz_nonzero" => {
748 assert_eq!(args.len(), 1);
749 let arg = args[0].load_value(fx);
750 let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
751 ret.write_cvalue(fx, res);
754 assert_eq!(args.len(), 1);
755 let arg = args[0].load_value(fx);
756 let res = CValue::ByVal(fx.bcx.ins().popcnt(arg), args[0].layout());
757 ret.write_cvalue(fx, res);
759 _ => unimpl!("unsupported intrinsic {}", intrinsic),
762 if let Some((_, dest)) = destination {
763 let ret_ebb = fx.get_ebb(dest);
764 fx.bcx.ins().jump(ret_ebb, &[]);
766 fx.bcx.ins().trap(TrapCode::User(!0));