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)) // First param is place to put return val
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(),
187 .map(|output_ty| vec![AbiParam::new(output_ty)])
188 .unwrap_or(Vec::new()),
189 call_conv: CallConv::SystemV,
193 .declare_function(&name, Linkage::Import, &sig)
197 .declare_func_in_func(func_id, &mut self.bcx.func);
198 let call_inst = self.bcx.ins().call(func_ref, args);
199 if output_ty.is_none() {
202 let results = self.bcx.inst_results(call_inst);
203 assert_eq!(results.len(), 1);
210 args: &[CValue<'tcx>],
213 let (input_tys, args): (Vec<_>, Vec<_>) = args
217 self.cton_type(arg.layout().ty).unwrap(),
218 arg.load_value(self),
221 let return_layout = self.layout_of(return_ty);
222 let return_ty = if let ty::Tuple(tup) = return_ty.sty {
224 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
228 Some(self.cton_type(return_ty).unwrap())
230 if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
231 CValue::ByVal(val, return_layout)
234 self.bcx.ins().iconst(self.module.pointer_type(), 0),
240 fn self_sig(&self) -> FnSig<'tcx> {
241 ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
244 fn return_type(&self) -> Ty<'tcx> {
245 self.self_sig().output()
249 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
250 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
253 let ssa_analyzed = crate::analyze::analyze(fx);
255 let ret_layout = fx.layout_of(fx.return_type());
256 let output_pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true);
257 let ret_param = match output_pass_mode {
258 PassMode::NoPass => None,
259 PassMode::ByVal(_) => None,
260 PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.module.pointer_type())),
272 let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
274 // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
275 if Some(local) == fx.mir.spread_arg {
276 // This argument (e.g. the last argument in the "rust-call" ABI)
277 // is a tuple that was spread at the ABI level and now we have
278 // to reconstruct it into a tuple local variable, from multiple
279 // individual function arguments.
281 let tupled_arg_tys = match arg_ty.sty {
282 ty::Tuple(ref tys) => tys,
283 _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
286 let mut ebb_params = Vec::new();
287 for arg_ty in tupled_arg_tys.iter() {
289 get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
290 ebb_params.push(fx.bcx.append_ebb_param(start_ebb, cton_type));
293 (local, ArgKind::Spread(ebb_params), arg_ty)
296 get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
299 ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, cton_type)),
303 }).collect::<Vec<(Local, ArgKind, Ty)>>();
305 fx.bcx.switch_to_block(start_ebb);
307 fx.top_nop = Some(fx.bcx.ins().nop());
308 fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
310 match output_pass_mode {
311 PassMode::NoPass => {
312 let null = fx.bcx.ins().iconst(fx.module.pointer_type(), 0);
313 //unimplemented!("pass mode nopass");
316 CPlace::Addr(null, None, fx.layout_of(fx.return_type())),
319 PassMode::ByVal(ret_ty) => {
320 fx.bcx.declare_var(mir_var(RETURN_PLACE), ret_ty);
322 .insert(RETURN_PLACE, CPlace::Var(RETURN_PLACE, ret_layout));
327 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
332 for (local, arg_kind, ty) in func_params {
333 let layout = fx.layout_of(ty);
335 if let ArgKind::Normal(ebb_param) = arg_kind {
339 .contains(crate::analyze::Flags::NOT_SSA)
342 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
343 match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false) {
344 PassMode::NoPass => unimplemented!("pass mode nopass"),
345 PassMode::ByVal(_) => fx.bcx.def_var(mir_var(local), ebb_param),
347 let val = CValue::ByRef(ebb_param, fx.layout_of(ty)).load_value(fx);
348 fx.bcx.def_var(mir_var(local), val);
351 fx.local_map.insert(local, CPlace::Var(local, layout));
356 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
357 kind: StackSlotKind::ExplicitSlot,
358 size: layout.size.bytes() as u32,
362 let place = CPlace::from_stack_slot(fx, stack_slot, ty);
365 ArgKind::Normal(ebb_param) => match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false)
367 PassMode::NoPass => unimplemented!("pass mode nopass"),
368 PassMode::ByVal(_) => {
369 place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()))
371 PassMode::ByRef => place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout())),
373 ArgKind::Spread(ebb_params) => {
374 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
375 let sub_place = place.place_field(fx, mir::Field::new(i));
376 match get_pass_mode(fx.tcx, fx.self_sig().abi, sub_place.layout().ty, false) {
377 PassMode::NoPass => unimplemented!("pass mode nopass"),
378 PassMode::ByVal(_) => {
379 sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()))
382 sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()))
388 fx.local_map.insert(local, place);
391 for local in fx.mir.vars_and_temps_iter() {
392 let ty = fx.mir.local_decls[local].ty;
393 let layout = fx.layout_of(ty);
395 let place = if ssa_analyzed
398 .contains(crate::analyze::Flags::NOT_SSA)
400 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
401 kind: StackSlotKind::ExplicitSlot,
402 size: layout.size.bytes() as u32,
405 CPlace::from_stack_slot(fx, stack_slot, ty)
408 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
409 CPlace::Var(local, layout)
412 fx.local_map.insert(local, place);
417 .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
420 pub fn codegen_call<'a, 'tcx: 'a>(
421 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
422 func: &Operand<'tcx>,
423 args: &[Operand<'tcx>],
424 destination: &Option<(Place<'tcx>, BasicBlock)>,
426 let fn_ty = fx.monomorphize(&func.ty(&fx.mir.local_decls, fx.tcx));
427 let sig = ty_fn_sig(fx.tcx, fn_ty);
429 // Unpack arguments tuple for closures
430 let args = if sig.abi == Abi::RustCall {
431 assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
432 let self_arg = trans_operand(fx, &args[0]);
433 let pack_arg = trans_operand(fx, &args[1]);
434 let mut args = Vec::new();
436 match pack_arg.layout().ty.sty {
437 ty::Tuple(ref tupled_arguments) => {
438 for (i, _) in tupled_arguments.iter().enumerate() {
439 args.push(pack_arg.value_field(fx, mir::Field::new(i)));
442 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
447 .map(|arg| trans_operand(fx, arg))
451 let destination = destination
453 .map(|(place, bb)| (trans_place(fx, place), *bb));
455 if codegen_intrinsic_call(fx, fn_ty, sig, &args, destination) {
459 let ret_layout = fx.layout_of(sig.output());
461 let output_pass_mode = get_pass_mode(fx.tcx, sig.abi, sig.output(), true);
462 let return_ptr = match output_pass_mode {
463 PassMode::NoPass => None,
464 PassMode::ByRef => match destination {
465 Some((place, _)) => Some(place.expect_addr()),
466 None => Some(fx.bcx.ins().iconst(fx.module.pointer_type(), 0)),
468 PassMode::ByVal(_) => None,
471 let call_args: Vec<Value> = return_ptr
473 .chain(args.into_iter().map(|arg| {
474 match get_pass_mode(fx.tcx, sig.abi, arg.layout().ty, false) {
475 PassMode::NoPass => unimplemented!("pass mode nopass"),
476 PassMode::ByVal(_) => arg.load_value(fx),
477 PassMode::ByRef => arg.force_stack(fx),
479 })).collect::<Vec<_>>();
481 let call_inst = match fn_ty.sty {
482 ty::FnDef(def_id, substs) => {
483 let inst = Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap();
484 let func_ref = fx.get_function_ref(inst);
485 fx.bcx.ins().call(func_ref, &call_args)
488 let func = trans_operand(fx, func);
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)
493 _ => bug!("{:?}", fn_ty),
496 match output_pass_mode {
497 PassMode::NoPass => {}
498 PassMode::ByVal(_) => {
499 if let Some((ret_place, _)) = destination {
500 let results = fx.bcx.inst_results(call_inst);
501 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
504 PassMode::ByRef => {}
506 if let Some((_, dest)) = destination {
507 let ret_ebb = fx.get_ebb(dest);
508 fx.bcx.ins().jump(ret_ebb, &[]);
510 fx.bcx.ins().trap(TrapCode::User(!0));
514 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
515 match get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true) {
516 PassMode::NoPass | PassMode::ByRef => {
517 fx.bcx.ins().return_(&[]);
519 PassMode::ByVal(_) => {
520 let place = fx.get_local_place(RETURN_PLACE);
521 let ret_val = place.to_cvalue(fx).load_value(fx);
522 fx.bcx.ins().return_(&[ret_val]);
527 fn codegen_intrinsic_call<'a, 'tcx: 'a>(
528 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
531 args: &[CValue<'tcx>],
532 destination: Option<(CPlace<'tcx>, BasicBlock)>,
534 if let ty::FnDef(def_id, substs) = fn_ty.sty {
535 if sig.abi == Abi::RustIntrinsic {
536 let intrinsic = fx.tcx.item_name(def_id).as_str();
537 let intrinsic = &intrinsic[..];
539 let ret = match destination {
540 Some((place, _)) => place,
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();
582 .iconst(fx.module.pointer_type(), elem_size as i64);
583 assert_eq!(args.len(), 3);
586 let count = args[2].load_value(fx);
587 let byte_amount = fx.bcx.ins().imul(count, elem_size);
590 &[dst, src, CValue::ByVal(byte_amount, usize_layout)],
594 "discriminant_value" => {
595 assert_eq!(args.len(), 1);
596 let discr = crate::base::trans_get_discriminant(fx, args[0], ret.layout());
597 ret.write_cvalue(fx, discr);
600 assert_eq!(args.len(), 0);
601 let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
602 let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
603 ret.write_cvalue(fx, size_of);
606 assert_eq!(args.len(), 1);
607 let size = match &substs.type_at(0).sty {
609 let len = args[0].load_value_pair(fx).1;
610 let elem_size = fx.layout_of(elem).size.bytes();
611 fx.bcx.ins().imul_imm(len, elem_size as i64)
613 ty => unimplemented!("size_of_val for {:?}", ty),
615 ret.write_cvalue(fx, CValue::ByVal(size, usize_layout));
618 assert_eq!(args.len(), 0);
619 let type_id = fx.tcx.type_id_hash(substs.type_at(0));
620 let type_id = CValue::const_val(fx, u64_layout.ty, type_id as i64);
621 ret.write_cvalue(fx, type_id);
624 assert_eq!(args.len(), 0);
625 let min_align = fx.layout_of(substs.type_at(0)).align.abi();
626 let min_align = CValue::const_val(fx, usize_layout.ty, min_align as i64);
627 ret.write_cvalue(fx, min_align);
629 _ if intrinsic.starts_with("unchecked_") => {
630 assert_eq!(args.len(), 2);
631 let bin_op = match intrinsic {
632 "unchecked_div" => BinOp::Div,
633 "unchecked_rem" => BinOp::Rem,
634 "unchecked_shl" => BinOp::Shl,
635 "unchecked_shr" => BinOp::Shr,
636 _ => unimplemented!("intrinsic {}", intrinsic),
638 let res = match ret.layout().ty.sty {
639 ty::Uint(_) => crate::base::trans_int_binop(
647 ty::Int(_) => crate::base::trans_int_binop(
657 ret.write_cvalue(fx, res);
659 _ if intrinsic.ends_with("_with_overflow") => {
660 assert_eq!(args.len(), 2);
661 assert_eq!(args[0].layout().ty, args[1].layout().ty);
662 let bin_op = match intrinsic {
663 "add_with_overflow" => BinOp::Add,
664 "sub_with_overflow" => BinOp::Sub,
665 "mul_with_overflow" => BinOp::Mul,
666 _ => unimplemented!("intrinsic {}", intrinsic),
668 let res = match args[0].layout().ty.sty {
669 ty::Uint(_) => crate::base::trans_checked_int_binop(
677 ty::Int(_) => crate::base::trans_checked_int_binop(
687 ret.write_cvalue(fx, res);
689 _ if intrinsic.starts_with("overflowing_") => {
690 assert_eq!(args.len(), 2);
691 assert_eq!(args[0].layout().ty, args[1].layout().ty);
692 let bin_op = match intrinsic {
693 "overflowing_add" => BinOp::Add,
694 "overflowing_sub" => BinOp::Sub,
695 "overflowing_mul" => BinOp::Mul,
696 _ => unimplemented!("intrinsic {}", intrinsic),
698 let res = match args[0].layout().ty.sty {
699 ty::Uint(_) => crate::base::trans_int_binop(
707 ty::Int(_) => crate::base::trans_int_binop(
717 ret.write_cvalue(fx, res);
720 assert_eq!(args.len(), 2);
721 let base = args[0].load_value(fx);
722 let offset = args[1].load_value(fx);
723 let res = fx.bcx.ins().iadd(base, offset);
724 ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
727 assert_eq!(args.len(), 1);
728 let src_ty = substs.type_at(0);
729 let dst_ty = substs.type_at(1);
730 assert_eq!(args[0].layout().ty, src_ty);
731 let addr = args[0].force_stack(fx);
732 let dst_layout = fx.layout_of(dst_ty);
733 ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
736 assert_eq!(args.len(), 0);
737 let ty = substs.type_at(0);
738 let layout = fx.layout_of(ty);
739 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
740 kind: StackSlotKind::ExplicitSlot,
741 size: layout.size.bytes() as u32,
745 let uninit_place = CPlace::from_stack_slot(fx, stack_slot, ty);
746 let uninit_val = uninit_place.to_cvalue(fx);
747 ret.write_cvalue(fx, uninit_val);
749 "ctlz" | "ctlz_nonzero" => {
750 assert_eq!(args.len(), 1);
751 let arg = args[0].load_value(fx);
752 let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
753 ret.write_cvalue(fx, res);
755 "cttz" | "cttz_nonzero" => {
756 assert_eq!(args.len(), 1);
757 let arg = args[0].load_value(fx);
758 let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
759 ret.write_cvalue(fx, res);
762 assert_eq!(args.len(), 1);
763 let arg = args[0].load_value(fx);
764 let res = CValue::ByVal(fx.bcx.ins().popcnt(arg), args[0].layout());
765 ret.write_cvalue(fx, res);
767 _ => unimpl!("unsupported intrinsic {}", intrinsic),
770 if let Some((_, dest)) = destination {
771 let ret_ebb = fx.get_ebb(dest);
772 fx.bcx.ins().jump(ret_ebb, &[]);
774 fx.bcx.ins().trap(TrapCode::User(!0));