1 #[cfg(debug_assertions)]
6 use rustc_target::spec::abi::Abi;
7 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
9 use cranelift_codegen::ir::AbiParam;
11 use self::pass_mode::*;
12 use crate::prelude::*;
14 pub(crate) use self::returning::{can_return_to_ssa_var, codegen_return};
16 // Copied from https://github.com/rust-lang/rust/blob/b2c1a606feb1fbdb0ac0acba76f881ef172ed474/src/librustc_middle/ty/layout.rs#L2287
17 pub(crate) fn fn_sig_for_fn_abi<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> ty::PolyFnSig<'tcx> {
18 let ty = instance.monomorphic_ty(tcx);
21 // Shims currently have type FnPtr. Not sure this should remain.
23 let mut sig = ty.fn_sig(tcx);
24 if let ty::InstanceDef::VtableShim(..) = instance.def {
25 // Modify `fn(self, ...)` to `fn(self: *mut Self, ...)`.
26 sig = sig.map_bound(|mut sig| {
27 let mut inputs_and_output = sig.inputs_and_output.to_vec();
28 inputs_and_output[0] = tcx.mk_mut_ptr(inputs_and_output[0]);
29 sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
35 ty::Closure(def_id, substs) => {
36 let sig = substs.as_closure().sig();
38 let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
39 sig.map_bound(|sig| tcx.mk_fn_sig(
40 std::iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
47 ty::Generator(_, substs, _) => {
48 let sig = substs.as_generator().poly_sig();
50 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
51 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
53 let pin_did = tcx.lang_items().pin_type().unwrap();
54 let pin_adt_ref = tcx.adt_def(pin_did);
55 let pin_substs = tcx.intern_substs(&[env_ty.into()]);
56 let env_ty = tcx.mk_adt(pin_adt_ref, pin_substs);
59 let state_did = tcx.lang_items().gen_state().unwrap();
60 let state_adt_ref = tcx.adt_def(state_did);
61 let state_substs = tcx.intern_substs(&[
65 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
68 [env_ty, sig.resume_ty].iter(),
71 rustc_hir::Unsafety::Normal,
72 rustc_target::spec::abi::Abi::Rust
76 _ => bug!("unexpected type {:?} in Instance::fn_sig", ty)
80 fn clif_sig_from_fn_sig<'tcx>(
82 triple: &target_lexicon::Triple,
85 requires_caller_location: bool,
87 let abi = match sig.abi {
88 Abi::System => Abi::C,
91 let (call_conv, inputs, output): (CallConv, Vec<Ty<'tcx>>, Ty<'tcx>) = match abi {
92 Abi::Rust => (CallConv::triple_default(triple), sig.inputs().to_vec(), sig.output()),
93 Abi::C | Abi::Unadjusted => (CallConv::triple_default(triple), sig.inputs().to_vec(), sig.output()),
95 assert_eq!(sig.inputs().len(), 2);
96 let extra_args = match sig.inputs().last().unwrap().kind {
97 ty::Tuple(ref tupled_arguments) => tupled_arguments,
98 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
100 let mut inputs: Vec<Ty<'tcx>> = vec![sig.inputs()[0]];
101 inputs.extend(extra_args.types());
102 (CallConv::triple_default(triple), inputs, sig.output())
104 Abi::System => unreachable!(),
105 Abi::RustIntrinsic => (CallConv::triple_default(triple), sig.inputs().to_vec(), sig.output()),
106 _ => unimplemented!("unsupported abi {:?}", sig.abi),
113 let mut layout = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
114 if i == 0 && is_vtable_fn {
115 // Virtual calls turn their self param into a thin pointer.
116 // See https://github.com/rust-lang/rust/blob/37b6a5e5e82497caf5353d9d856e4eb5d14cbe06/src/librustc/ty/layout.rs#L2519-L2572 for more info
118 .layout_of(ParamEnv::reveal_all().and(tcx.mk_mut_ptr(tcx.mk_unit())))
121 get_pass_mode(tcx, layout).get_param_ty(tcx).into_iter()
125 let (mut params, returns): (Vec<_>, Vec<_>) = match get_pass_mode(
127 tcx.layout_of(ParamEnv::reveal_all().and(output)).unwrap(),
129 PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
130 PassMode::ByVal(ret_ty) => (
131 inputs.map(AbiParam::new).collect(),
132 vec![AbiParam::new(ret_ty)],
134 PassMode::ByValPair(ret_ty_a, ret_ty_b) => (
135 inputs.map(AbiParam::new).collect(),
136 vec![AbiParam::new(ret_ty_a), AbiParam::new(ret_ty_b)],
138 PassMode::ByRef { sized: true } => {
140 Some(pointer_ty(tcx)) // First param is place to put return val
148 PassMode::ByRef { sized: false } => todo!(),
151 if requires_caller_location {
152 params.push(AbiParam::new(pointer_ty(tcx)));
162 pub(crate) fn get_function_name_and_sig<'tcx>(
164 triple: &target_lexicon::Triple,
165 inst: Instance<'tcx>,
166 support_vararg: bool,
167 ) -> (String, Signature) {
168 assert!(!inst.substs.needs_infer());
170 tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &fn_sig_for_fn_abi(tcx, inst));
171 if fn_sig.c_variadic && !support_vararg {
172 unimpl_fatal!(tcx, tcx.def_span(inst.def_id()), "Variadic function definitions are not yet supported");
174 let sig = clif_sig_from_fn_sig(tcx, triple, fn_sig, false, inst.def.requires_caller_location(tcx));
175 (tcx.symbol_name(inst).name.as_str().to_string(), sig)
178 /// Instance must be monomorphized
179 pub(crate) fn import_function<'tcx>(
181 module: &mut Module<impl Backend>,
182 inst: Instance<'tcx>,
184 let (name, sig) = get_function_name_and_sig(tcx, module.isa().triple(), inst, true);
186 .declare_function(&name, Linkage::Import, &sig)
190 impl<'tcx, B: Backend + 'static> FunctionCx<'_, 'tcx, B> {
191 /// Instance must be monomorphized
192 pub(crate) fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
193 let func_id = import_function(self.tcx, self.module, inst);
196 .declare_func_in_func(func_id, &mut self.bcx.func);
198 #[cfg(debug_assertions)]
199 self.add_comment(func_ref, format!("{:?}", inst));
204 pub(crate) fn lib_call(
207 input_tys: Vec<types::Type>,
208 output_tys: Vec<types::Type>,
211 let sig = Signature {
212 params: input_tys.iter().cloned().map(AbiParam::new).collect(),
213 returns: output_tys.iter().cloned().map(AbiParam::new).collect(),
214 call_conv: CallConv::triple_default(self.triple()),
218 .declare_function(&name, Linkage::Import, &sig)
222 .declare_func_in_func(func_id, &mut self.bcx.func);
223 let call_inst = self.bcx.ins().call(func_ref, args);
224 #[cfg(debug_assertions)]
226 self.add_comment(call_inst, format!("easy_call {}", name));
228 let results = self.bcx.inst_results(call_inst);
229 assert!(results.len() <= 2, "{}", results.len());
233 pub(crate) fn easy_call(
236 args: &[CValue<'tcx>],
239 let (input_tys, args): (Vec<_>, Vec<_>) = args
243 self.clif_type(arg.layout().ty).unwrap(),
244 arg.load_scalar(self),
248 let return_layout = self.layout_of(return_ty);
249 let return_tys = if let ty::Tuple(tup) = return_ty.kind {
250 tup.types().map(|ty| self.clif_type(ty).unwrap()).collect()
252 vec![self.clif_type(return_ty).unwrap()]
254 let ret_vals = self.lib_call(name, input_tys, return_tys, &args);
256 [] => CValue::by_ref(
257 Pointer::const_addr(self, self.pointer_type.bytes() as i64),
260 [val] => CValue::by_val(val, return_layout),
261 [val, extra] => CValue::by_val_pair(val, extra, return_layout),
267 fn local_place<'tcx>(
268 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
270 layout: TyAndLayout<'tcx>,
273 let place = if is_ssa {
274 CPlace::new_var(fx, local, layout)
276 CPlace::new_stack_slot(fx, layout)
279 #[cfg(debug_assertions)]
280 self::comments::add_local_place_comments(fx, place, local);
282 let prev_place = fx.local_map.insert(local, place);
283 debug_assert!(prev_place.is_none());
287 pub(crate) fn codegen_fn_prelude<'tcx>(
288 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
290 should_codegen_locals: bool,
292 let ssa_analyzed = crate::analyze::analyze(fx);
294 #[cfg(debug_assertions)]
295 self::comments::add_args_header_comment(fx);
297 self::returning::codegen_return_param(fx, &ssa_analyzed, start_block);
299 // None means pass_mode == NoPass
301 Normal(Option<CValue<'tcx>>),
302 Spread(Vec<Option<CValue<'tcx>>>),
309 let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
311 // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
312 if Some(local) == fx.mir.spread_arg {
313 // This argument (e.g. the last argument in the "rust-call" ABI)
314 // is a tuple that was spread at the ABI level and now we have
315 // to reconstruct it into a tuple local variable, from multiple
316 // individual function arguments.
318 let tupled_arg_tys = match arg_ty.kind {
319 ty::Tuple(ref tys) => tys,
320 _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
323 let mut params = Vec::new();
324 for (i, arg_ty) in tupled_arg_tys.types().enumerate() {
325 let param = cvalue_for_param(fx, start_block, Some(local), Some(i), arg_ty);
329 (local, ArgKind::Spread(params), arg_ty)
331 let param = cvalue_for_param(fx, start_block, Some(local), None, arg_ty);
332 (local, ArgKind::Normal(param), arg_ty)
335 .collect::<Vec<(Local, ArgKind<'tcx>, Ty<'tcx>)>>();
337 assert!(fx.caller_location.is_none());
338 if fx.instance.def.requires_caller_location(fx.tcx) {
339 // Store caller location for `#[track_caller]`.
340 fx.caller_location = Some(cvalue_for_param(fx, start_block, None, None, fx.tcx.caller_location_ty()).unwrap());
343 fx.bcx.switch_to_block(start_block);
346 #[cfg(debug_assertions)]
347 self::comments::add_locals_header_comment(fx);
349 for (local, arg_kind, ty) in func_params {
350 let layout = fx.layout_of(ty);
352 let is_ssa = ssa_analyzed[local] == crate::analyze::SsaKind::Ssa;
354 // While this is normally an optimization to prevent an unnecessary copy when an argument is
355 // not mutated by the current function, this is necessary to support unsized arguments.
357 ArgKind::Normal(Some(val)) => {
358 if let Some((addr, meta)) = val.try_to_ptr() {
359 let local_decl = &fx.mir.local_decls[local];
360 // v this ! is important
361 let internally_mutable = !val.layout().ty.is_freeze(
363 ParamEnv::reveal_all(),
364 local_decl.source_info.span,
366 if local_decl.mutability == mir::Mutability::Not && !internally_mutable {
367 // We wont mutate this argument, so it is fine to borrow the backing storage
368 // of this argument, to prevent a copy.
370 let place = if let Some(meta) = meta {
371 CPlace::for_ptr_with_extra(addr, meta, val.layout())
373 CPlace::for_ptr(addr, val.layout())
376 #[cfg(debug_assertions)]
377 self::comments::add_local_place_comments(fx, place, local);
379 let prev_place = fx.local_map.insert(local, place);
380 debug_assert!(prev_place.is_none());
388 let place = local_place(fx, local, layout, is_ssa);
391 ArgKind::Normal(param) => {
392 if let Some(param) = param {
393 place.write_cvalue(fx, param);
396 ArgKind::Spread(params) => {
397 for (i, param) in params.into_iter().enumerate() {
398 if let Some(param) = param {
400 .place_field(fx, mir::Field::new(i))
401 .write_cvalue(fx, param);
408 // HACK should_codegen_locals required for the ``implement `<Box<F> as FnOnce>::call_once`
409 // without `alloca``` hack in `base::trans_fn`.
410 if should_codegen_locals {
411 for local in fx.mir.vars_and_temps_iter() {
412 let ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
413 let layout = fx.layout_of(ty);
415 let is_ssa = ssa_analyzed[local] == crate::analyze::SsaKind::Ssa;
417 local_place(fx, local, layout, is_ssa);
423 .jump(*fx.block_map.get(START_BLOCK).unwrap(), &[]);
426 pub(crate) fn codegen_terminator_call<'tcx>(
427 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
429 current_block: Block,
430 func: &Operand<'tcx>,
431 args: &[Operand<'tcx>],
432 destination: Option<(Place<'tcx>, BasicBlock)>,
434 let fn_ty = fx.monomorphize(&func.ty(fx.mir, fx.tcx));
437 .normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &fn_ty.fn_sig(fx.tcx));
439 let destination = destination.map(|(place, bb)| (trans_place(fx, place), bb));
441 // Handle special calls like instrinsics and empty drop glue.
442 let instance = if let ty::FnDef(def_id, substs) = fn_ty.kind {
443 let instance = ty::Instance::resolve(fx.tcx, ty::ParamEnv::reveal_all(), def_id, substs)
447 if fx.tcx.symbol_name(instance).name.as_str().starts_with("llvm.") {
448 crate::intrinsics::codegen_llvm_intrinsic_call(
450 &fx.tcx.symbol_name(instance).name.as_str(),
459 InstanceDef::Intrinsic(_) => {
460 crate::intrinsics::codegen_intrinsic_call(fx, instance, args, destination, span);
463 InstanceDef::DropGlue(_, None) => {
464 // empty drop glue - a nop.
465 let (_, dest) = destination.expect("Non terminating drop_in_place_real???");
466 let ret_block = fx.get_block(dest);
467 fx.bcx.ins().jump(ret_block, &[]);
478 fx.tcx.codegen_fn_attrs(inst.def_id())
479 .flags.contains(CodegenFnAttrFlags::COLD))
482 fx.cold_blocks.insert(current_block);
485 // Unpack arguments tuple for closures
486 let args = if fn_sig.abi == Abi::RustCall {
487 assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
488 let self_arg = trans_operand(fx, &args[0]);
489 let pack_arg = trans_operand(fx, &args[1]);
491 let tupled_arguments = match pack_arg.layout().ty.kind {
492 ty::Tuple(ref tupled_arguments) => {
495 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
498 let mut args = Vec::with_capacity(1 + tupled_arguments.len());
500 for i in 0..tupled_arguments.len() {
501 args.push(pack_arg.value_field(fx, mir::Field::new(i)));
506 .map(|arg| trans_operand(fx, arg))
510 // | indirect call target
511 // | | the first argument to be passed
512 // v v v virtual calls are special cased below
513 let (func_ref, first_arg, is_virtual_call) = match instance {
516 def: InstanceDef::Virtual(_, idx),
519 #[cfg(debug_assertions)]
521 let nop_inst = fx.bcx.ins().nop();
525 "virtual call; self arg pass mode: {:?}",
526 get_pass_mode(fx.tcx, args[0].layout())
530 let (ptr, method) = crate::vtable::get_ptr_and_method_ref(fx, args[0], idx);
531 (Some(method), Single(ptr), true)
538 .map(|arg| adjust_arg_for_abi(fx, *arg))
545 #[cfg(debug_assertions)]
547 let nop_inst = fx.bcx.ins().nop();
548 fx.add_comment(nop_inst, "indirect call");
550 let func = trans_operand(fx, func)
555 .map(|arg| adjust_arg_for_abi(fx, *arg))
562 let ret_place = destination.map(|(place, _)| place);
563 let (call_inst, call_args) =
564 self::returning::codegen_with_call_return_arg(fx, fn_sig, ret_place, |fx, return_ptr| {
565 let mut call_args: Vec<Value> = return_ptr
567 .chain(first_arg.into_iter())
571 .map(|arg| adjust_arg_for_abi(fx, arg).into_iter())
574 .collect::<Vec<_>>();
576 if instance.map(|inst| inst.def.requires_caller_location(fx.tcx)).unwrap_or(false) {
577 // Pass the caller location for `#[track_caller]`.
578 let caller_location = fx.get_caller_location(span);
579 call_args.extend(adjust_arg_for_abi(fx, caller_location).into_iter());
582 let call_inst = if let Some(func_ref) = func_ref {
583 let sig = clif_sig_from_fn_sig(
588 false, // calls through function pointers never pass the caller location
590 let sig = fx.bcx.import_signature(sig);
591 fx.bcx.ins().call_indirect(sig, func_ref, &call_args)
594 fx.get_function_ref(instance.expect("non-indirect call on non-FnDef type"));
595 fx.bcx.ins().call(func_ref, &call_args)
598 (call_inst, call_args)
601 // FIXME find a cleaner way to support varargs
602 if fn_sig.c_variadic {
603 if fn_sig.abi != Abi::C {
604 unimpl_fatal!(fx.tcx, span, "Variadic call for non-C abi {:?}", fn_sig.abi);
606 let sig_ref = fx.bcx.func.dfg.call_signature(call_inst).unwrap();
607 let abi_params = call_args
610 let ty = fx.bcx.func.dfg.value_type(arg);
612 // FIXME set %al to upperbound on float args once floats are supported
613 unimpl_fatal!(fx.tcx, span, "Non int ty {:?} for variadic call", ty);
617 .collect::<Vec<AbiParam>>();
618 fx.bcx.func.dfg.signatures[sig_ref].params = abi_params;
621 if let Some((_, dest)) = destination {
622 let ret_block = fx.get_block(dest);
623 fx.bcx.ins().jump(ret_block, &[]);
625 trap_unreachable(fx, "[corruption] Diverging function returned");
629 pub(crate) fn codegen_drop<'tcx>(
630 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
632 drop_place: CPlace<'tcx>,
634 let ty = drop_place.layout().ty;
635 let drop_fn = Instance::resolve_drop_in_place(fx.tcx, ty);
637 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
638 // we don't actually need to drop anything
640 let drop_fn_ty = drop_fn.monomorphic_ty(fx.tcx);
641 let fn_sig = fx.tcx.normalize_erasing_late_bound_regions(
642 ParamEnv::reveal_all(),
643 &drop_fn_ty.fn_sig(fx.tcx),
645 assert_eq!(fn_sig.output(), fx.tcx.mk_unit());
649 let (ptr, vtable) = drop_place.to_ptr_maybe_unsized();
650 let ptr = ptr.get_addr(fx);
651 let drop_fn = crate::vtable::drop_fn_of_obj(fx, vtable.unwrap());
653 let sig = clif_sig_from_fn_sig(
658 false, // `drop_in_place` is never `#[track_caller]`
660 let sig = fx.bcx.import_signature(sig);
661 fx.bcx.ins().call_indirect(sig, drop_fn, &[ptr]);
664 let instance = match drop_fn_ty.kind {
665 ty::FnDef(def_id, substs) => {
666 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
670 _ => unreachable!("{:?}", drop_fn_ty),
673 assert!(!matches!(instance.def, InstanceDef::Virtual(_, _)));
675 let arg_place = CPlace::new_stack_slot(
677 fx.layout_of(fx.tcx.mk_ref(
678 &ty::RegionKind::ReErased,
681 mutbl: crate::rustc_hir::Mutability::Mut,
685 drop_place.write_place_ref(fx, arg_place);
686 let arg_value = arg_place.to_cvalue(fx);
687 let arg_value = adjust_arg_for_abi(fx, arg_value);
689 let mut call_args: Vec<Value> = arg_value.into_iter().collect::<Vec<_>>();
691 if instance.def.requires_caller_location(fx.tcx) {
692 // Pass the caller location for `#[track_caller]`.
693 let caller_location = fx.get_caller_location(span);
694 call_args.extend(adjust_arg_for_abi(fx, caller_location).into_iter());
697 let func_ref = fx.get_function_ref(instance);
698 fx.bcx.ins().call(func_ref, &call_args);