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 => 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()),
58 assert_eq!(sig.inputs().len(), 2);
59 let extra_args = match sig.inputs().last().unwrap().sty {
60 ty::TyTuple(ref tupled_arguments) => tupled_arguments,
61 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
63 let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
64 inputs.extend(extra_args.into_iter());
65 (CallConv::Fast, inputs, sig.output())
67 Abi::System => bug!("system abi should be selected elsewhere"),
68 Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
69 _ => unimplemented!("unsupported abi {:?}", sig.abi),
74 .filter_map(|ty| match get_pass_mode(tcx, sig.abi, ty, false) {
75 PassMode::ByVal(cton_ty) => Some(cton_ty),
76 PassMode::NoPass => unimplemented!("pass mode nopass"),
77 PassMode::ByRef => Some(types::I64),
80 let (params, returns) = match get_pass_mode(tcx, sig.abi, output, true) {
81 PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
82 PassMode::ByVal(ret_ty) => (
83 inputs.map(AbiParam::new).collect(),
84 vec![AbiParam::new(ret_ty)],
88 Some(types::I64).into_iter() // First param is place to put return val
101 argument_bytes: None,
105 fn ty_fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> ty::FnSig<'tcx> {
106 let sig = match ty.sty {
108 // Shims currently have type TyFnPtr. Not sure this should remain.
109 ty::TyFnPtr(_) => ty.fn_sig(tcx),
110 ty::TyClosure(def_id, substs) => {
111 let sig = substs.closure_sig(def_id, tcx);
113 let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
114 sig.map_bound(|sig| tcx.mk_fn_sig(
115 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
122 ty::TyGenerator(def_id, substs, _) => {
123 let sig = substs.poly_sig(def_id, tcx);
125 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
126 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
128 sig.map_bound(|sig| {
129 let state_did = tcx.lang_items().gen_state().unwrap();
130 let state_adt_ref = tcx.adt_def(state_did);
131 let state_substs = tcx.intern_substs(&[
133 sig.return_ty.into(),
135 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
137 tcx.mk_fn_sig(iter::once(env_ty),
140 hir::Unsafety::Normal,
145 _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
147 tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
150 pub fn get_function_name_and_sig<'a, 'tcx>(
151 tcx: TyCtxt<'a, 'tcx, 'tcx>,
152 inst: Instance<'tcx>,
153 ) -> (String, Signature) {
154 assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
155 let fn_ty = inst.ty(tcx);
156 let sig = cton_sig_from_fn_ty(tcx, fn_ty);
157 (tcx.symbol_name(inst).as_str().to_string(), sig)
160 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
161 /// Instance must be monomorphized
162 pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
163 let (name, sig) = get_function_name_and_sig(self.tcx, inst);
166 .declare_function(&name, Linkage::Import, &sig)
169 .declare_func_in_func(func_id, &mut self.bcx.func)
175 input_tys: Vec<types::Type>,
176 output_ty: Option<types::Type>,
179 let sig = Signature {
180 params: input_tys.iter().cloned().map(AbiParam::new).collect(),
181 returns: vec![AbiParam::new(output_ty.unwrap_or(types::VOID))],
182 call_conv: CallConv::SystemV,
183 argument_bytes: None,
187 .declare_function(&name, Linkage::Import, &sig)
191 .declare_func_in_func(func_id, &mut self.bcx.func);
192 let call_inst = self.bcx.ins().call(func_ref, args);
193 if output_ty.is_none() {
196 let results = self.bcx.inst_results(call_inst);
197 assert_eq!(results.len(), 1);
204 args: &[CValue<'tcx>],
207 let (input_tys, args): (Vec<_>, Vec<_>) = args
211 self.cton_type(arg.layout().ty).unwrap(),
212 arg.load_value(self),
215 let return_layout = self.layout_of(return_ty);
216 let return_ty = if let TypeVariants::TyTuple(tup) = return_ty.sty {
218 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
222 Some(self.cton_type(return_ty).unwrap())
224 if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
225 CValue::ByVal(val, return_layout)
227 CValue::ByRef(self.bcx.ins().iconst(types::I64, 0), return_layout)
231 fn self_sig(&self) -> FnSig<'tcx> {
232 ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
235 fn return_type(&self) -> Ty<'tcx> {
236 self.self_sig().output()
240 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
241 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
244 let ssa_analyzed = crate::analyze::analyze(fx);
246 match fx.self_sig().abi {
247 Abi::Rust | Abi::RustCall => {}
248 _ => unimplemented!("declared function with non \"rust\" or \"rust-call\" abi"),
251 let ret_layout = fx.layout_of(fx.return_type());
252 let output_pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true);
253 let ret_param = match output_pass_mode {
254 PassMode::NoPass => None,
255 PassMode::ByVal(_) => None,
256 PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, types::I64)),
268 let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
270 // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
271 if Some(local) == fx.mir.spread_arg {
272 // This argument (e.g. the last argument in the "rust-call" ABI)
273 // is a tuple that was spread at the ABI level and now we have
274 // to reconstruct it into a tuple local variable, from multiple
275 // individual function arguments.
277 let tupled_arg_tys = match arg_ty.sty {
278 ty::TyTuple(ref tys) => tys,
279 _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
282 let mut ebb_params = Vec::new();
283 for arg_ty in tupled_arg_tys.iter() {
285 get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
286 ebb_params.push(fx.bcx.append_ebb_param(start_ebb, cton_type));
289 (local, ArgKind::Spread(ebb_params), arg_ty)
292 get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
295 ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, cton_type)),
299 }).collect::<Vec<(Local, ArgKind, Ty)>>();
301 fx.bcx.switch_to_block(start_ebb);
303 fx.top_nop = Some(fx.bcx.ins().nop());
304 fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
306 match output_pass_mode {
307 PassMode::NoPass => {
308 let null = fx.bcx.ins().iconst(types::I64, 0);
309 //unimplemented!("pass mode nopass");
312 CPlace::Addr(null, fx.layout_of(fx.return_type())),
315 PassMode::ByVal(ret_ty) => {
316 fx.bcx.declare_var(mir_var(RETURN_PLACE), ret_ty);
318 .insert(RETURN_PLACE, CPlace::Var(RETURN_PLACE, ret_layout));
322 .insert(RETURN_PLACE, CPlace::Addr(ret_param.unwrap(), ret_layout));
326 for (local, arg_kind, ty) in func_params {
327 let layout = fx.layout_of(ty);
329 if let ArgKind::Normal(ebb_param) = arg_kind {
333 .contains(crate::analyze::Flags::NOT_SSA)
336 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
337 match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false) {
338 PassMode::NoPass => unimplemented!("pass mode nopass"),
339 PassMode::ByVal(_) => fx.bcx.def_var(mir_var(local), ebb_param),
341 let val = CValue::ByRef(ebb_param, fx.layout_of(ty)).load_value(fx);
342 fx.bcx.def_var(mir_var(local), val);
345 fx.local_map.insert(local, CPlace::Var(local, layout));
350 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
351 kind: StackSlotKind::ExplicitSlot,
352 size: layout.size.bytes() as u32,
356 let place = CPlace::from_stack_slot(fx, stack_slot, ty);
359 ArgKind::Normal(ebb_param) => match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false)
361 PassMode::NoPass => unimplemented!("pass mode nopass"),
362 PassMode::ByVal(_) => {
363 place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()))
365 PassMode::ByRef => place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout())),
367 ArgKind::Spread(ebb_params) => {
368 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
369 let sub_place = place.place_field(fx, mir::Field::new(i));
370 match get_pass_mode(fx.tcx, fx.self_sig().abi, sub_place.layout().ty, false) {
371 PassMode::NoPass => unimplemented!("pass mode nopass"),
372 PassMode::ByVal(_) => {
373 sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()))
376 sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()))
382 fx.local_map.insert(local, place);
385 for local in fx.mir.vars_and_temps_iter() {
386 let ty = fx.mir.local_decls[local].ty;
387 let layout = fx.layout_of(ty);
389 let place = if ssa_analyzed
392 .contains(crate::analyze::Flags::NOT_SSA)
394 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
395 kind: StackSlotKind::ExplicitSlot,
396 size: layout.size.bytes() as u32,
399 CPlace::from_stack_slot(fx, stack_slot, ty)
402 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
403 CPlace::Var(local, layout)
406 fx.local_map.insert(local, place);
411 .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
414 pub fn codegen_call<'a, 'tcx: 'a>(
415 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
416 func: &Operand<'tcx>,
417 args: &[Operand<'tcx>],
418 destination: &Option<(Place<'tcx>, BasicBlock)>,
420 let fn_ty = fx.monomorphize(&func.ty(&fx.mir.local_decls, fx.tcx));
421 let sig = ty_fn_sig(fx.tcx, fn_ty);
423 // Unpack arguments tuple for closures
424 let args = if sig.abi == Abi::RustCall {
425 assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
426 let self_arg = trans_operand(fx, &args[0]);
427 let pack_arg = trans_operand(fx, &args[1]);
428 let mut args = Vec::new();
430 match pack_arg.layout().ty.sty {
431 ty::TyTuple(ref tupled_arguments) => {
432 for (i, _) in tupled_arguments.iter().enumerate() {
433 args.push(pack_arg.value_field(fx, mir::Field::new(i)));
436 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
441 .map(|arg| trans_operand(fx, arg))
445 let destination = destination
447 .map(|(place, bb)| (trans_place(fx, place), *bb));
449 if codegen_intrinsic_call(fx, fn_ty, sig, &args, destination) {
453 let ret_layout = fx.layout_of(sig.output());
455 let output_pass_mode = get_pass_mode(fx.tcx, sig.abi, sig.output(), true);
456 let return_ptr = match output_pass_mode {
457 PassMode::NoPass => None,
458 PassMode::ByRef => match destination {
459 Some((place, _)) => Some(place.expect_addr()),
460 None => Some(fx.bcx.ins().iconst(types::I64, 0)),
462 PassMode::ByVal(_) => None,
465 let call_args: Vec<Value> = return_ptr
467 .chain(args.into_iter().map(|arg| {
468 match get_pass_mode(fx.tcx, sig.abi, arg.layout().ty, false) {
469 PassMode::NoPass => unimplemented!("pass mode nopass"),
470 PassMode::ByVal(_) => arg.load_value(fx),
471 PassMode::ByRef => arg.force_stack(fx),
473 })).collect::<Vec<_>>();
475 let inst = match trans_operand(fx, func) {
476 CValue::Func(func, _) => fx.bcx.ins().call(func, &call_args),
478 let func = func.load_value(fx);
479 let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, fn_ty));
480 fx.bcx.ins().call_indirect(sig, func, &call_args)
484 match output_pass_mode {
485 PassMode::NoPass => {}
486 PassMode::ByVal(_) => {
487 if let Some((ret_place, _)) = destination {
488 let results = fx.bcx.inst_results(inst);
489 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
492 PassMode::ByRef => {}
494 if let Some((_, dest)) = destination {
495 let ret_ebb = fx.get_ebb(dest);
496 fx.bcx.ins().jump(ret_ebb, &[]);
498 fx.bcx.ins().trap(TrapCode::User(!0));
502 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
503 match get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true) {
504 PassMode::NoPass | PassMode::ByRef => {
505 fx.bcx.ins().return_(&[]);
507 PassMode::ByVal(_) => {
508 let place = fx.get_local_place(RETURN_PLACE);
509 let ret_val = place.to_cvalue(fx).load_value(fx);
510 fx.bcx.ins().return_(&[ret_val]);
515 fn codegen_intrinsic_call<'a, 'tcx: 'a>(
516 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
519 args: &[CValue<'tcx>],
520 destination: Option<(CPlace<'tcx>, BasicBlock)>,
522 if let TypeVariants::TyFnDef(def_id, substs) = fn_ty.sty {
523 if sig.abi == Abi::RustIntrinsic {
524 let intrinsic = fx.tcx.item_name(def_id).as_str();
525 let intrinsic = &intrinsic[..];
527 let ret = match destination {
528 Some((place, _)) => place,
530 // Insert non returning intrinsics here
533 fx.bcx.ins().trap(TrapCode::User(!0 - 1));
536 fx.bcx.ins().trap(TrapCode::User(!0 - 1));
538 _ => unimplemented!("unsupported instrinsic {}", intrinsic),
544 let nil_ty = fx.tcx.mk_nil();
545 let u64_layout = fx.layout_of(fx.tcx.types.u64);
546 let usize_layout = fx.layout_of(fx.tcx.types.usize);
550 assert_eq!(args.len(), 1);
553 assert_eq!(args.len(), 2);
554 let base = args[0].load_value(fx);
555 let offset = args[1].load_value(fx);
556 let res = fx.bcx.ins().iadd(base, offset);
557 let res = CValue::ByVal(res, ret.layout());
558 ret.write_cvalue(fx, res);
560 "likely" | "unlikely" => {
561 assert_eq!(args.len(), 1);
562 ret.write_cvalue(fx, args[0]);
564 "copy" | "copy_nonoverlapping" => {
565 let elem_ty = substs.type_at(0);
566 let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
567 let elem_size = fx.bcx.ins().iconst(types::I64, elem_size as i64);
568 assert_eq!(args.len(), 3);
571 let count = args[2].load_value(fx);
572 let byte_amount = fx.bcx.ins().imul(count, elem_size);
575 &[dst, src, CValue::ByVal(byte_amount, usize_layout)],
579 "discriminant_value" => {
580 assert_eq!(args.len(), 1);
581 let discr = crate::base::trans_get_discriminant(fx, args[0], ret.layout());
582 ret.write_cvalue(fx, discr);
585 assert_eq!(args.len(), 0);
586 let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
587 let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
588 ret.write_cvalue(fx, size_of);
591 assert_eq!(args.len(), 0);
592 let type_id = fx.tcx.type_id_hash(substs.type_at(0));
593 let type_id = CValue::const_val(fx, u64_layout.ty, type_id as i64);
594 ret.write_cvalue(fx, type_id);
597 assert_eq!(args.len(), 0);
598 let min_align = fx.layout_of(substs.type_at(0)).align.abi();
599 let min_align = CValue::const_val(fx, usize_layout.ty, min_align as i64);
600 ret.write_cvalue(fx, min_align);
602 _ if intrinsic.starts_with("unchecked_") => {
603 assert_eq!(args.len(), 2);
604 let bin_op = match intrinsic {
605 "unchecked_div" => BinOp::Div,
606 "unchecked_rem" => BinOp::Rem,
607 "unchecked_shl" => BinOp::Shl,
608 "unchecked_shr" => BinOp::Shr,
609 _ => unimplemented!("intrinsic {}", intrinsic),
611 let res = match ret.layout().ty.sty {
612 TypeVariants::TyUint(_) => crate::base::trans_int_binop(
620 TypeVariants::TyInt(_) => crate::base::trans_int_binop(
630 ret.write_cvalue(fx, res);
632 _ if intrinsic.ends_with("_with_overflow") => {
633 assert_eq!(args.len(), 2);
634 assert_eq!(args[0].layout().ty, args[1].layout().ty);
635 let bin_op = match intrinsic {
636 "add_with_overflow" => BinOp::Add,
637 "sub_with_overflow" => BinOp::Sub,
638 "mul_with_overflow" => BinOp::Mul,
639 _ => unimplemented!("intrinsic {}", intrinsic),
641 let res = match args[0].layout().ty.sty {
642 TypeVariants::TyUint(_) => crate::base::trans_checked_int_binop(
650 TypeVariants::TyInt(_) => crate::base::trans_checked_int_binop(
660 ret.write_cvalue(fx, res);
662 _ if intrinsic.starts_with("overflowing_") => {
663 assert_eq!(args.len(), 2);
664 assert_eq!(args[0].layout().ty, args[1].layout().ty);
665 let bin_op = match intrinsic {
666 "overflowing_add" => BinOp::Add,
667 "overflowing_sub" => BinOp::Sub,
668 "overflowing_mul" => BinOp::Mul,
669 _ => unimplemented!("intrinsic {}", intrinsic),
671 let res = match args[0].layout().ty.sty {
672 TypeVariants::TyUint(_) => crate::base::trans_int_binop(
680 TypeVariants::TyInt(_) => crate::base::trans_int_binop(
690 ret.write_cvalue(fx, res);
693 assert_eq!(args.len(), 2);
694 let base = args[0].load_value(fx);
695 let offset = args[1].load_value(fx);
696 let res = fx.bcx.ins().iadd(base, offset);
697 ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
700 assert_eq!(args.len(), 1);
701 let src_ty = substs.type_at(0);
702 let dst_ty = substs.type_at(1);
703 assert_eq!(args[0].layout().ty, src_ty);
704 let addr = args[0].force_stack(fx);
705 let dst_layout = fx.layout_of(dst_ty);
706 ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
709 assert_eq!(args.len(), 0);
710 let ty = substs.type_at(0);
711 let layout = fx.layout_of(ty);
712 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
713 kind: StackSlotKind::ExplicitSlot,
714 size: layout.size.bytes() as u32,
718 let uninit_place = CPlace::from_stack_slot(fx, stack_slot, ty);
719 let uninit_val = uninit_place.to_cvalue(fx);
720 ret.write_cvalue(fx, uninit_val);
722 "ctlz" | "ctlz_nonzero" => {
723 assert_eq!(args.len(), 1);
724 let arg = args[0].load_value(fx);
725 let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
726 ret.write_cvalue(fx, res);
728 "cttz" | "cttz_nonzero" => {
729 assert_eq!(args.len(), 1);
730 let arg = args[0].load_value(fx);
731 let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
732 ret.write_cvalue(fx, res);
735 assert_eq!(args.len(), 1);
736 let arg = args[0].load_value(fx);
737 let res = CValue::ByVal(fx.bcx.ins().popcnt(arg), args[0].layout());
738 ret.write_cvalue(fx, res);
740 _ => unimpl!("unsupported intrinsic {}", intrinsic),
743 if let Some((_, dest)) = destination {
744 let ret_ebb = fx.get_ebb(dest);
745 fx.bcx.ins().jump(ret_ebb, &[]);
747 fx.bcx.ins().trap(TrapCode::User(!0));