4 use rustc_target::spec::abi::Abi;
16 fn get_param_ty(self, _fx: &FunctionCx) -> Type {
18 PassMode::NoPass => unimplemented!("pass mode nopass"),
19 PassMode::ByVal(cton_type) => cton_type,
20 PassMode::ByRef => types::I64,
25 fn get_pass_mode<'a, 'tcx: 'a>(
26 tcx: TyCtxt<'a, 'tcx, 'tcx>,
31 if ty.sty == tcx.mk_nil().sty {
38 } else if let Some(ret_ty) = crate::common::cton_type_from_ty(tcx, ty) {
39 PassMode::ByVal(ret_ty)
42 unimplemented!("Non scalars are not yet supported for \"C\" abi");
48 pub fn cton_sig_from_fn_ty<'a, 'tcx: 'a>(
49 tcx: TyCtxt<'a, 'tcx, 'tcx>,
52 let sig = ty_fn_sig(tcx, fn_ty);
53 assert!(!sig.variadic, "Variadic function are not yet supported");
54 let (call_conv, inputs, output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
55 Abi::Rust => (CallConv::Fast, sig.inputs().to_vec(), sig.output()),
56 Abi::C => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
59 "rust-call sig: {:?} inputs: {:?} output: {:?}",
64 assert_eq!(sig.inputs().len(), 2);
65 let extra_args = match sig.inputs().last().unwrap().sty {
66 ty::TyTuple(ref tupled_arguments) => tupled_arguments,
67 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
69 let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
70 inputs.extend(extra_args.into_iter());
71 (CallConv::Fast, inputs, sig.output())
73 Abi::System => bug!("system abi should be selected elsewhere"),
74 Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
75 _ => unimplemented!("unsupported abi {:?}", sig.abi),
80 .filter_map(|ty| match get_pass_mode(tcx, sig.abi, ty, false) {
81 PassMode::ByVal(cton_ty) => Some(cton_ty),
82 PassMode::NoPass => unimplemented!("pass mode nopass"),
83 PassMode::ByRef => Some(types::I64),
86 let (params, returns) = match get_pass_mode(tcx, sig.abi, output, true) {
87 PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
88 PassMode::ByVal(ret_ty) => (
89 inputs.map(AbiParam::new).collect(),
90 vec![AbiParam::new(ret_ty)],
94 Some(types::I64).into_iter() // First param is place to put return val
107 argument_bytes: None,
111 fn ty_fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> ty::FnSig<'tcx> {
112 let sig = match ty.sty {
114 // Shims currently have type TyFnPtr. Not sure this should remain.
115 ty::TyFnPtr(_) => ty.fn_sig(tcx),
116 ty::TyClosure(def_id, substs) => {
117 let sig = substs.closure_sig(def_id, tcx);
119 let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
120 sig.map_bound(|sig| tcx.mk_fn_sig(
121 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
128 ty::TyGenerator(def_id, substs, _) => {
129 let sig = substs.poly_sig(def_id, tcx);
131 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
132 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
134 sig.map_bound(|sig| {
135 let state_did = tcx.lang_items().gen_state().unwrap();
136 let state_adt_ref = tcx.adt_def(state_did);
137 let state_substs = tcx.intern_substs(&[
139 sig.return_ty.into(),
141 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
143 tcx.mk_fn_sig(iter::once(env_ty),
146 hir::Unsafety::Normal,
151 _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
153 tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
156 pub fn get_function_name_and_sig<'a, 'tcx>(
157 tcx: TyCtxt<'a, 'tcx, 'tcx>,
158 inst: Instance<'tcx>,
159 ) -> (String, Signature) {
160 assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
161 let fn_ty = inst.ty(tcx);
162 let sig = cton_sig_from_fn_ty(tcx, fn_ty);
163 let def_path_based_names =
164 ::rustc_mir::monomorphize::item::DefPathBasedNames::new(tcx, false, false);
165 let mut name = String::new();
166 def_path_based_names.push_instance_as_string(inst, &mut name);
170 impl<'a, 'tcx: 'a> CodegenCx<'a, 'tcx, CurrentBackend> {
171 pub fn predefine_function(&mut self, inst: Instance<'tcx>) -> (FuncId, Function) {
172 let (name, sig) = crate::abi::get_function_name_and_sig(self.tcx, inst);
175 .declare_function(&name, Linkage::Export, &sig)
178 Function::with_name_signature(ExternalName::user(0, func_id.index() as u32), sig);
183 impl<'a, 'tcx: 'a> FunctionCx<'a, 'tcx> {
184 /// Instance must be monomorphized
185 pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
186 let (name, sig) = get_function_name_and_sig(self.tcx, inst);
189 .declare_function(&name, Linkage::Import, &sig)
192 .declare_func_in_func(func_id, &mut self.bcx.func)
198 input_tys: Vec<types::Type>,
199 output_ty: Option<types::Type>,
202 let sig = Signature {
203 params: input_tys.iter().cloned().map(AbiParam::new).collect(),
204 returns: vec![AbiParam::new(output_ty.unwrap_or(types::VOID))],
205 call_conv: CallConv::SystemV,
206 argument_bytes: None,
210 .declare_function(&name, Linkage::Import, &sig)
214 .declare_func_in_func(func_id, &mut self.bcx.func);
215 let call_inst = self.bcx.ins().call(func_ref, args);
216 if output_ty.is_none() {
219 let results = self.bcx.inst_results(call_inst);
220 assert_eq!(results.len(), 1);
227 args: &[CValue<'tcx>],
230 let (input_tys, args): (Vec<_>, Vec<_>) = args
234 self.cton_type(arg.layout().ty).unwrap(),
235 arg.load_value(self),
238 let return_layout = self.layout_of(return_ty);
239 let return_ty = if let TypeVariants::TyTuple(tup) = return_ty.sty {
241 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
245 Some(self.cton_type(return_ty).unwrap())
247 if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
248 CValue::ByVal(val, return_layout)
250 CValue::ByRef(self.bcx.ins().iconst(types::I64, 0), return_layout)
254 fn self_sig(&self) -> FnSig<'tcx> {
255 ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
258 fn return_type(&self) -> Ty<'tcx> {
259 self.self_sig().output()
263 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, start_ebb: Ebb) {
264 let ssa_analyzed = crate::analyze::analyze(fx);
265 fx.tcx.sess.warn(&format!("ssa {:?}", ssa_analyzed));
267 match fx.self_sig().abi {
268 Abi::Rust | Abi::RustCall => {}
269 _ => unimplemented!("declared function with non \"rust\" or \"rust-call\" abi"),
272 let ret_layout = fx.layout_of(fx.return_type());
273 let output_pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true);
274 let ret_param = match output_pass_mode {
275 PassMode::NoPass => None,
276 PassMode::ByVal(ret_ty) => None,
277 PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, types::I64)),
285 let func_params = fx.mir.args_iter().map(|local| {
286 let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
288 // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
289 if Some(local) == fx.mir.spread_arg {
290 // This argument (e.g. the last argument in the "rust-call" ABI)
291 // is a tuple that was spread at the ABI level and now we have
292 // to reconstruct it into a tuple local variable, from multiple
293 // individual function arguments.
295 let tupled_arg_tys = match arg_ty.sty {
296 ty::TyTuple(ref tys) => tys,
297 _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
300 let mut ebb_params = Vec::new();
301 for arg_ty in tupled_arg_tys.iter() {
302 let cton_type = get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
303 ebb_params.push(fx.bcx.append_ebb_param(start_ebb, cton_type));
306 (local, ArgKind::Spread(ebb_params), arg_ty)
308 let cton_type = get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
309 (local, ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, cton_type)), arg_ty)
311 }).collect::<Vec<(Local, ArgKind, Ty)>>();
313 match output_pass_mode {
314 PassMode::NoPass => {
315 let null = fx.bcx.ins().iconst(types::I64, 0);
316 //unimplemented!("pass mode nopass");
319 CPlace::Addr(null, fx.layout_of(fx.return_type())),
322 PassMode::ByVal(ret_ty) => {
323 let var = Variable(RETURN_PLACE);
324 fx.bcx.declare_var(var, ret_ty);
326 .insert(RETURN_PLACE, CPlace::Var(var, ret_layout));
330 .insert(RETURN_PLACE, CPlace::Addr(ret_param.unwrap(), ret_layout));
334 for (local, arg_kind, ty) in func_params {
335 let layout = fx.layout_of(ty);
337 if let ArgKind::Normal(ebb_param) = arg_kind {
341 .contains(crate::analyze::Flags::NOT_SSA)
343 let var = Variable(local);
344 fx.bcx.declare_var(var, fx.cton_type(ty).unwrap());
345 match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false) {
346 PassMode::NoPass => unimplemented!("pass mode nopass"),
347 PassMode::ByVal(_) => fx.bcx.def_var(var, ebb_param),
349 let val = CValue::ByRef(ebb_param, fx.layout_of(ty)).load_value(fx);
350 fx.bcx.def_var(var, val);
353 fx.local_map.insert(local, CPlace::Var(var, layout));
358 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
359 kind: StackSlotKind::ExplicitSlot,
360 size: layout.size.bytes() as u32,
364 let place = CPlace::from_stack_slot(fx, stack_slot, ty);
367 ArgKind::Normal(ebb_param) => match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false)
369 PassMode::NoPass => unimplemented!("pass mode nopass"),
370 PassMode::ByVal(_) => {
371 place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()))
373 PassMode::ByRef => place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout())),
375 ArgKind::Spread(ebb_params) => {
376 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
377 let sub_place = place.place_field(fx, mir::Field::new(i));
378 match get_pass_mode(fx.tcx, fx.self_sig().abi, sub_place.layout().ty, false) {
379 PassMode::NoPass => unimplemented!("pass mode nopass"),
380 PassMode::ByVal(_) => {
381 sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()))
384 sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()))
390 fx.local_map.insert(local, place);
393 for local in fx.mir.vars_and_temps_iter() {
394 let ty = fx.mir.local_decls[local].ty;
395 let layout = fx.layout_of(ty);
397 let place = if ssa_analyzed
400 .contains(crate::analyze::Flags::NOT_SSA)
402 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
403 kind: StackSlotKind::ExplicitSlot,
404 size: layout.size.bytes() as u32,
407 CPlace::from_stack_slot(fx, stack_slot, ty)
409 let var = Variable(local);
410 fx.bcx.declare_var(var, fx.cton_type(ty).unwrap());
411 CPlace::Var(var, layout)
414 fx.local_map.insert(local, place);
418 pub fn codegen_call<'a, 'tcx: 'a>(
419 fx: &mut FunctionCx<'a, 'tcx>,
420 func: &Operand<'tcx>,
421 args: &[Operand<'tcx>],
422 destination: &Option<(Place<'tcx>, BasicBlock)>,
424 let func = trans_operand(fx, func);
425 let fn_ty = func.layout().ty;
426 let sig = ty_fn_sig(fx.tcx, fn_ty);
428 // Unpack arguments tuple for closures
429 let args = if sig.abi == Abi::RustCall {
430 assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
431 let self_arg = trans_operand(fx, &args[0]);
432 let pack_arg = trans_operand(fx, &args[1]);
433 let mut args = Vec::new();
435 match pack_arg.layout().ty.sty {
436 ty::TyTuple(ref tupled_arguments) => {
437 for (i, _) in tupled_arguments.iter().enumerate() {
438 args.push(pack_arg.value_field(fx, mir::Field::new(i)));
441 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
445 pack_arg.layout().ty,
446 args.iter().map(|a| a.layout().ty).collect::<Vec<_>>()
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 println!("{:?}", output_pass_mode);
467 let return_ptr = match output_pass_mode {
468 PassMode::NoPass => None,
469 PassMode::ByRef => match destination {
470 Some((place, _)) => Some(place.expect_addr()),
471 None => Some(fx.bcx.ins().iconst(types::I64, 0)),
473 PassMode::ByVal(_) => None,
476 let call_args: Vec<Value> = return_ptr
478 .chain(args.into_iter().map(|arg| {
479 match get_pass_mode(fx.tcx, sig.abi, arg.layout().ty, false) {
480 PassMode::NoPass => unimplemented!("pass mode nopass"),
481 PassMode::ByVal(_) => arg.load_value(fx),
482 PassMode::ByRef => arg.force_stack(fx),
484 })).collect::<Vec<_>>();
486 let inst = match func {
487 CValue::Func(func, _) => fx.bcx.ins().call(func, &call_args),
489 let func = func.load_value(fx);
490 let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, fn_ty));
491 fx.bcx.ins().call_indirect(sig, func, &call_args)
495 match output_pass_mode {
496 PassMode::NoPass => {}
497 PassMode::ByVal(_) => {
498 if let Some((ret_place, _)) = destination {
499 let results = fx.bcx.inst_results(inst);
500 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
503 PassMode::ByRef => {}
505 if let Some((_, dest)) = destination {
506 let ret_ebb = fx.get_ebb(dest);
507 fx.bcx.ins().jump(ret_ebb, &[]);
509 fx.bcx.ins().trap(TrapCode::User(!0));
513 pub fn codegen_return(fx: &mut FunctionCx) {
514 match get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true) {
515 PassMode::NoPass | PassMode::ByRef => {
516 fx.bcx.ins().return_(&[]);
518 PassMode::ByVal(_) => {
519 let place = fx.get_local_place(RETURN_PLACE);
520 let ret_val = place.to_cvalue(fx).load_value(fx);
521 fx.bcx.ins().return_(&[ret_val]);
526 fn codegen_intrinsic_call<'a, 'tcx: 'a>(
527 fx: &mut FunctionCx<'a, 'tcx>,
530 args: &[CValue<'tcx>],
531 destination: Option<(CPlace<'tcx>, BasicBlock)>,
533 if let TypeVariants::TyFnDef(def_id, substs) = fn_ty.sty {
534 if sig.abi == Abi::RustIntrinsic {
535 let intrinsic = fx.tcx.item_name(def_id).as_str();
536 let intrinsic = &intrinsic[..];
538 let ret = match destination {
539 Some((place, _)) => place,
541 println!("codegen_call(fx, _, {:?}, {:?})", args, destination);
542 // Insert non returning intrinsics here
545 fx.bcx.ins().trap(TrapCode::User(!0 - 1));
548 fx.bcx.ins().trap(TrapCode::User(!0 - 1));
550 _ => unimplemented!("unsupported instrinsic {}", intrinsic),
556 let nil_ty = fx.tcx.mk_nil();
557 let u64_layout = fx.layout_of(fx.tcx.types.u64);
558 let usize_layout = fx.layout_of(fx.tcx.types.usize);
562 assert_eq!(args.len(), 1);
565 assert_eq!(args.len(), 2);
566 let base = args[0].load_value(fx);
567 let offset = args[1].load_value(fx);
568 let res = fx.bcx.ins().iadd(base, offset);
569 let res = CValue::ByVal(res, ret.layout());
570 ret.write_cvalue(fx, res);
572 "likely" | "unlikely" => {
573 assert_eq!(args.len(), 1);
574 ret.write_cvalue(fx, args[0]);
576 "copy" | "copy_nonoverlapping" => {
577 let elem_ty = substs.type_at(0);
578 let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
579 let elem_size = fx.bcx.ins().iconst(types::I64, elem_size as i64);
580 assert_eq!(args.len(), 3);
583 let count = args[2].load_value(fx);
584 let byte_amount = fx.bcx.ins().imul(count, elem_size);
587 &[dst, src, CValue::ByVal(byte_amount, usize_layout)],
591 "discriminant_value" => {
592 assert_eq!(args.len(), 1);
593 let discr = crate::base::trans_get_discriminant(fx, args[0], ret.layout());
594 ret.write_cvalue(fx, discr);
597 assert_eq!(args.len(), 0);
598 let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
599 let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
600 ret.write_cvalue(fx, size_of);
603 assert_eq!(args.len(), 0);
604 let type_id = fx.tcx.type_id_hash(substs.type_at(0));
605 let type_id = CValue::const_val(fx, u64_layout.ty, type_id as i64);
606 ret.write_cvalue(fx, type_id);
609 assert_eq!(args.len(), 0);
610 let min_align = fx.layout_of(substs.type_at(0)).align.abi();
611 let min_align = CValue::const_val(fx, usize_layout.ty, min_align as i64);
612 ret.write_cvalue(fx, min_align);
614 _ if intrinsic.starts_with("unchecked_") => {
615 assert_eq!(args.len(), 2);
616 let bin_op = match intrinsic {
617 "unchecked_div" => BinOp::Div,
618 "unchecked_rem" => BinOp::Rem,
619 "unchecked_shl" => BinOp::Shl,
620 "unchecked_shr" => BinOp::Shr,
621 _ => unimplemented!("intrinsic {}", intrinsic),
623 let res = match ret.layout().ty.sty {
624 TypeVariants::TyUint(_) => crate::base::trans_int_binop(
632 TypeVariants::TyInt(_) => crate::base::trans_int_binop(
642 ret.write_cvalue(fx, res);
644 _ if intrinsic.ends_with("_with_overflow") => {
645 assert_eq!(args.len(), 2);
646 assert_eq!(args[0].layout().ty, args[1].layout().ty);
647 let bin_op = match intrinsic {
648 "add_with_overflow" => BinOp::Add,
649 "sub_with_overflow" => BinOp::Sub,
650 "mul_with_overflow" => BinOp::Mul,
651 _ => unimplemented!("intrinsic {}", intrinsic),
653 let res = match args[0].layout().ty.sty {
654 TypeVariants::TyUint(_) => crate::base::trans_checked_int_binop(
662 TypeVariants::TyInt(_) => crate::base::trans_checked_int_binop(
672 ret.write_cvalue(fx, res);
674 _ if intrinsic.starts_with("overflowing_") => {
675 assert_eq!(args.len(), 2);
676 assert_eq!(args[0].layout().ty, args[1].layout().ty);
677 let bin_op = match intrinsic {
678 "overflowing_add" => BinOp::Add,
679 "overflowing_sub" => BinOp::Sub,
680 "overflowing_mul" => BinOp::Mul,
681 _ => unimplemented!("intrinsic {}", intrinsic),
683 let res = match args[0].layout().ty.sty {
684 TypeVariants::TyUint(_) => crate::base::trans_int_binop(
692 TypeVariants::TyInt(_) => crate::base::trans_int_binop(
702 ret.write_cvalue(fx, res);
705 assert_eq!(args.len(), 2);
706 let base = args[0].load_value(fx);
707 let offset = args[1].load_value(fx);
708 let res = fx.bcx.ins().iadd(base, offset);
709 ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
712 assert_eq!(args.len(), 1);
713 let src_ty = substs.type_at(0);
714 let dst_ty = substs.type_at(1);
715 assert_eq!(args[0].layout().ty, src_ty);
716 let addr = args[0].force_stack(fx);
717 let dst_layout = fx.layout_of(dst_ty);
718 ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
721 assert_eq!(args.len(), 0);
722 let ty = substs.type_at(0);
723 let layout = fx.layout_of(ty);
724 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
725 kind: StackSlotKind::ExplicitSlot,
726 size: layout.size.bytes() as u32,
730 let uninit_place = CPlace::from_stack_slot(fx, stack_slot, ty);
731 let uninit_val = uninit_place.to_cvalue(fx);
732 ret.write_cvalue(fx, uninit_val);
734 "ctlz" | "ctlz_nonzero" => {
735 assert_eq!(args.len(), 1);
736 let arg = args[0].load_value(fx);
737 let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
738 ret.write_cvalue(fx, res);
740 "cttz" | "cttz_nonzero" => {
741 assert_eq!(args.len(), 1);
742 let arg = args[0].load_value(fx);
743 let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
744 ret.write_cvalue(fx, res);
747 assert_eq!(args.len(), 1);
748 let arg = args[0].load_value(fx);
749 let res = CValue::ByVal(fx.bcx.ins().popcnt(arg), args[0].layout());
750 ret.write_cvalue(fx, res);
752 _ => unimpl!("unsupported intrinsic {}", intrinsic),
755 if let Some((_, dest)) = destination {
756 let ret_ebb = fx.get_ebb(dest);
757 fx.bcx.ins().jump(ret_ebb, &[]);
759 fx.bcx.ins().trap(TrapCode::User(!0));