rust/src/abi.rs

878 lines
28 KiB
Rust
Raw Normal View History

use std::borrow::Cow;
2018-07-19 19:33:42 +02:00
2019-02-21 15:06:09 +01:00
use rustc::ty::layout::{FloatTy, Integer, Primitive, Scalar};
use rustc_target::spec::abi::Abi;
2018-07-19 19:33:42 +02:00
use crate::prelude::*;
2018-07-19 19:33:42 +02:00
2018-12-25 16:47:33 +01:00
#[derive(Copy, Clone, Debug)]
enum PassMode {
NoPass,
ByVal(Type),
2019-06-16 12:54:37 +02:00
ByValPair(Type, Type),
ByRef,
}
2019-06-16 12:54:37 +02:00
#[derive(Copy, Clone, Debug)]
enum EmptySinglePair<T> {
Empty,
Single(T),
Pair(T, T),
}
impl<T> EmptySinglePair<T> {
fn into_iter(self) -> EmptySinglePairIter<T> {
EmptySinglePairIter(self)
}
fn map<U>(self, mut f: impl FnMut(T) -> U) -> EmptySinglePair<U> {
match self {
Empty => Empty,
Single(v) => Single(f(v)),
Pair(a, b) => Pair(f(a), f(b)),
}
}
}
struct EmptySinglePairIter<T>(EmptySinglePair<T>);
impl<T> Iterator for EmptySinglePairIter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
match std::mem::replace(&mut self.0, Empty) {
Empty => None,
Single(v) => Some(v),
Pair(a, b) => {
self.0 = Single(b);
Some(a)
}
}
}
}
impl<T: std::fmt::Debug> EmptySinglePair<T> {
fn assert_single(self) -> T {
match self {
Single(v) => v,
_ => panic!("Called assert_single on {:?}", self)
}
}
fn assert_pair(self) -> (T, T) {
match self {
Pair(a, b) => (a, b),
_ => panic!("Called assert_pair on {:?}", self)
}
}
}
use EmptySinglePair::*;
impl PassMode {
2019-06-16 12:54:37 +02:00
fn get_param_ty(self, fx: &FunctionCx<impl Backend>) -> EmptySinglePair<Type> {
match self {
2019-06-16 12:54:37 +02:00
PassMode::NoPass => Empty,
PassMode::ByVal(clif_type) => Single(clif_type),
PassMode::ByValPair(a, b) => Pair(a, b),
PassMode::ByRef => Single(fx.pointer_type),
}
}
}
pub fn scalar_to_clif_type(tcx: TyCtxt, scalar: Scalar) -> Type {
match scalar.value {
Primitive::Int(int, _sign) => match int {
Integer::I8 => types::I8,
Integer::I16 => types::I16,
Integer::I32 => types::I32,
Integer::I64 => types::I64,
Integer::I128 => unimpl!("u/i128"),
2019-02-21 15:06:09 +01:00
},
Primitive::Float(flt) => match flt {
FloatTy::F32 => types::F32,
FloatTy::F64 => types::F64,
2019-02-21 15:06:09 +01:00
},
Primitive::Pointer => pointer_ty(tcx),
}
}
fn get_pass_mode<'tcx>(
tcx: TyCtxt<'tcx>,
2019-06-16 12:54:37 +02:00
layout: TyLayout<'tcx>,
) -> PassMode {
2019-01-02 14:03:56 +01:00
assert!(!layout.is_unsized());
if layout.is_zst() {
// WARNING zst arguments must never be passed, as that will break CastKind::ClosureFnPointer
PassMode::NoPass
} else {
2019-01-02 14:03:56 +01:00
match &layout.abi {
layout::Abi::Uninhabited => PassMode::NoPass,
2019-02-21 15:06:09 +01:00
layout::Abi::Scalar(scalar) => {
PassMode::ByVal(scalar_to_clif_type(tcx, scalar.clone()))
}
2019-06-16 12:54:37 +02:00
layout::Abi::ScalarPair(a, b) => {
PassMode::ByValPair(
scalar_to_clif_type(tcx, a.clone()),
scalar_to_clif_type(tcx, b.clone()),
)
}
2019-01-02 14:03:56 +01:00
2019-06-16 12:54:37 +02:00
// FIXME implement Vector Abi in a cg_llvm compatible way
2019-01-02 14:03:56 +01:00
layout::Abi::Vector { .. } => PassMode::ByRef,
layout::Abi::Aggregate { .. } => PassMode::ByRef,
}
}
}
2018-09-08 18:00:06 +02:00
fn adjust_arg_for_abi<'a, 'tcx: 'a>(
fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
arg: CValue<'tcx>,
2019-06-16 12:54:37 +02:00
) -> EmptySinglePair<Value> {
match get_pass_mode(fx.tcx, arg.layout()) {
PassMode::NoPass => Empty,
PassMode::ByVal(_) => Single(arg.load_scalar(fx)),
PassMode::ByValPair(_, _) => {
let (a, b) = arg.load_scalar_pair(fx);
Pair(a, b)
}
PassMode::ByRef => Single(arg.force_stack(fx)),
2018-09-08 18:00:06 +02:00
}
}
2019-06-16 12:54:37 +02:00
fn clif_sig_from_fn_sig<'tcx>(tcx: TyCtxt<'tcx>, sig: FnSig<'tcx>, is_vtable_fn: bool) -> Signature {
let (call_conv, inputs, output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
Abi::Rust => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
Abi::C => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
Abi::RustCall => {
assert_eq!(sig.inputs().len(), 2);
2018-07-20 13:38:49 +02:00
let extra_args = match sig.inputs().last().unwrap().sty {
ty::Tuple(ref tupled_arguments) => tupled_arguments,
2018-07-20 13:38:49 +02:00
_ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
};
let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
inputs.extend(extra_args.types());
(CallConv::SystemV, inputs, sig.output())
}
Abi::System => bug!("system abi should be selected elsewhere"),
2018-07-20 14:20:37 +02:00
Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
_ => unimplemented!("unsupported abi {:?}", sig.abi),
2018-07-19 19:33:42 +02:00
};
let inputs = inputs
.into_iter()
2019-06-16 12:54:37 +02:00
.enumerate()
.map(|(i, ty)| {
let mut layout = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
if i == 0 && is_vtable_fn {
// Virtual calls turn their self param into a thin pointer.
2019-06-16 17:27:51 +02:00
// See https://github.com/rust-lang/rust/blob/37b6a5e5e82497caf5353d9d856e4eb5d14cbe06/src/librustc/ty/layout.rs#L2519-L2572 for more info
2019-06-16 12:54:37 +02:00
layout = tcx.layout_of(ParamEnv::reveal_all().and(tcx.mk_mut_ptr(tcx.mk_unit()))).unwrap();
}
match get_pass_mode(tcx, layout) {
PassMode::NoPass => Empty,
PassMode::ByVal(clif_ty) => Single(clif_ty),
PassMode::ByValPair(clif_ty_a, clif_ty_b) => Pair(clif_ty_a, clif_ty_b),
PassMode::ByRef => Single(pointer_ty(tcx)),
}.into_iter()
}).flatten();
let (params, returns) = match get_pass_mode(tcx, tcx.layout_of(ParamEnv::reveal_all().and(output)).unwrap()) {
PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
PassMode::ByVal(ret_ty) => (
inputs.map(AbiParam::new).collect(),
vec![AbiParam::new(ret_ty)],
),
2019-06-16 12:54:37 +02:00
PassMode::ByValPair(ret_ty_a, ret_ty_b) => (
inputs.map(AbiParam::new).collect(),
vec![AbiParam::new(ret_ty_a), AbiParam::new(ret_ty_b)],
),
PassMode::ByRef => {
(
2018-09-08 17:24:52 +02:00
Some(pointer_ty(tcx)) // First param is place to put return val
.into_iter()
.chain(inputs)
.map(AbiParam::new)
.collect(),
vec![],
)
}
};
2018-07-19 19:33:42 +02:00
Signature {
params,
returns,
2018-07-19 19:33:42 +02:00
call_conv,
}
}
pub fn get_function_name_and_sig<'tcx>(
tcx: TyCtxt<'tcx>,
2018-08-11 13:59:08 +02:00
inst: Instance<'tcx>,
2019-02-21 15:06:09 +01:00
support_vararg: bool,
2018-08-11 13:59:08 +02:00
) -> (String, Signature) {
assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
let fn_sig = tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &inst.fn_sig(tcx));
if fn_sig.c_variadic && !support_vararg {
2019-02-11 19:18:52 +01:00
unimpl!("Variadic function definitions are not yet supported");
2019-01-02 12:20:32 +01:00
}
2019-06-16 12:54:37 +02:00
let sig = clif_sig_from_fn_sig(tcx, fn_sig, false);
2018-08-11 14:29:32 +02:00
(tcx.symbol_name(inst).as_str().to_string(), sig)
2018-08-11 13:59:08 +02:00
}
2019-01-02 12:20:32 +01:00
/// Instance must be monomorphized
pub fn import_function<'tcx>(
tcx: TyCtxt<'tcx>,
2019-01-02 12:20:32 +01:00
module: &mut Module<impl Backend>,
inst: Instance<'tcx>,
) -> FuncId {
2019-02-11 19:18:52 +01:00
let (name, sig) = get_function_name_and_sig(tcx, inst, true);
2019-01-02 12:20:32 +01:00
module
.declare_function(&name, Linkage::Import, &sig)
.unwrap()
}
2018-09-08 18:00:06 +02:00
2019-01-02 12:20:32 +01:00
impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
2018-09-08 18:00:06 +02:00
/// Instance must be monomorphized
pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
2019-01-02 12:20:32 +01:00
let func_id = import_function(self.tcx, self.module, inst);
2019-02-21 15:06:09 +01:00
let func_ref = self
.module
2018-12-27 10:59:01 +01:00
.declare_func_in_func(func_id, &mut self.bcx.func);
2018-12-28 17:07:40 +01:00
#[cfg(debug_assertions)]
2018-12-27 10:59:01 +01:00
self.add_entity_comment(func_ref, format!("{:?}", inst));
2018-12-28 17:07:40 +01:00
2018-12-27 10:59:01 +01:00
func_ref
2018-07-19 19:33:42 +02:00
}
fn lib_call(
2018-07-30 15:34:34 +02:00
&mut self,
name: &str,
input_tys: Vec<types::Type>,
output_ty: Option<types::Type>,
2018-07-30 15:34:34 +02:00
args: &[Value],
) -> Option<Value> {
2018-07-30 15:34:34 +02:00
let sig = Signature {
params: input_tys.iter().cloned().map(AbiParam::new).collect(),
2018-09-08 17:24:52 +02:00
returns: output_ty
.map(|output_ty| vec![AbiParam::new(output_ty)])
.unwrap_or(Vec::new()),
2018-07-30 15:34:34 +02:00
call_conv: CallConv::SystemV,
};
let func_id = self
.module
.declare_function(&name, Linkage::Import, &sig)
.unwrap();
let func_ref = self
.module
.declare_func_in_func(func_id, &mut self.bcx.func);
2018-07-30 15:34:34 +02:00
let call_inst = self.bcx.ins().call(func_ref, args);
if output_ty.is_none() {
return None;
}
2018-07-30 15:34:34 +02:00
let results = self.bcx.inst_results(call_inst);
assert_eq!(results.len(), 1);
Some(results[0])
2018-07-30 15:34:34 +02:00
}
pub fn easy_call(
&mut self,
name: &str,
args: &[CValue<'tcx>],
return_ty: Ty<'tcx>,
) -> CValue<'tcx> {
let (input_tys, args): (Vec<_>, Vec<_>) = args
.into_iter()
.map(|arg| {
(
2018-11-12 07:23:39 -08:00
self.clif_type(arg.layout().ty).unwrap(),
arg.load_scalar(self),
)
2018-10-10 19:07:13 +02:00
})
.unzip();
2018-07-30 15:34:34 +02:00
let return_layout = self.layout_of(return_ty);
let return_ty = if let ty::Tuple(tup) = return_ty.sty {
if !tup.is_empty() {
bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
}
None
} else {
2018-11-12 07:23:39 -08:00
Some(self.clif_type(return_ty).unwrap())
};
if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
2019-06-11 15:32:30 +02:00
CValue::by_val(val, return_layout)
} else {
2019-06-11 15:32:30 +02:00
CValue::by_ref(
2019-02-21 15:06:09 +01:00
self.bcx
.ins()
.iconst(self.pointer_type, self.pointer_type.bytes() as i64),
return_layout,
)
}
2018-07-30 15:34:34 +02:00
}
fn self_sig(&self) -> FnSig<'tcx> {
self.tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &self.instance.fn_sig(self.tcx))
}
2019-06-16 12:54:37 +02:00
fn return_layout(&self) -> TyLayout<'tcx> {
self.layout_of(self.self_sig().output())
}
2018-07-19 19:33:42 +02:00
}
2018-12-28 17:07:40 +01:00
#[cfg(debug_assertions)]
2018-12-27 10:59:01 +01:00
fn add_arg_comment<'a, 'tcx: 'a>(
fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
msg: &str,
local: mir::Local,
local_field: Option<usize>,
2019-06-16 12:54:37 +02:00
params: EmptySinglePair<Value>,
2018-12-27 10:59:01 +01:00
pass_mode: PassMode,
ssa: crate::analyze::Flags,
ty: Ty<'tcx>,
) {
let local_field = if let Some(local_field) = local_field {
Cow::Owned(format!(".{}", local_field))
} else {
Cow::Borrowed("")
};
2019-06-16 12:54:37 +02:00
let params = match params {
Empty => Cow::Borrowed("-"),
Single(param) => Cow::Owned(format!("= {:?}", param)),
Pair(param_a, param_b) => Cow::Owned(format!("= {:?}, {:?}", param_a, param_b)),
};
2018-12-27 10:59:01 +01:00
let pass_mode = format!("{:?}", pass_mode);
fx.add_global_comment(format!(
2019-06-16 12:54:37 +02:00
"{msg:5} {local:>3}{local_field:<5} {params:10} {pass_mode:20} {ssa:10} {ty:?}",
2019-02-21 15:06:09 +01:00
msg = msg,
local = format!("{:?}", local),
local_field = local_field,
2019-06-16 12:54:37 +02:00
params = params,
2019-02-21 15:06:09 +01:00
pass_mode = pass_mode,
ssa = format!("{:?}", ssa),
ty = ty,
));
}
2018-12-28 17:07:40 +01:00
#[cfg(debug_assertions)]
fn add_local_header_comment(fx: &mut FunctionCx<impl Backend>) {
2019-02-21 15:06:09 +01:00
fx.add_global_comment(format!(
"msg loc.idx param pass mode ssa flags ty"
));
}
2018-12-26 11:15:42 +01:00
fn local_place<'a, 'tcx: 'a>(
2018-12-25 16:47:33 +01:00
fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
local: Local,
layout: TyLayout<'tcx>,
is_ssa: bool,
) -> CPlace<'tcx> {
let place = if is_ssa {
2019-06-11 15:32:30 +02:00
CPlace::new_var(fx, local, layout)
2018-12-25 16:47:33 +01:00
} else {
2019-02-04 19:27:58 +01:00
let place = CPlace::new_stack_slot(fx, layout.ty);
2018-12-25 16:47:33 +01:00
2018-12-28 17:07:40 +01:00
#[cfg(debug_assertions)]
{
let TyLayout { ty, details } = layout;
2019-02-21 15:06:09 +01:00
let ty::layout::LayoutDetails {
size,
align,
abi: _,
variants: _,
fields: _,
} = details;
2019-02-04 19:58:07 +01:00
match place {
2019-02-21 15:06:09 +01:00
CPlace::Stack(stack_slot, _) => fx.add_entity_comment(
stack_slot,
format!(
"{:?}: {:?} size={} align={},{}",
local,
ty,
size.bytes(),
align.abi.bytes(),
align.pref.bytes(),
),
),
2019-02-04 19:58:07 +01:00
CPlace::NoPlace(_) => fx.add_global_comment(format!(
"zst {:?}: {:?} size={} align={}, {}",
2019-02-21 15:06:09 +01:00
local,
ty,
size.bytes(),
align.abi.bytes(),
align.pref.bytes(),
2019-02-04 19:58:07 +01:00
)),
2019-02-04 19:27:58 +01:00
_ => unreachable!(),
2019-02-06 19:07:21 +01:00
}
2018-12-28 17:07:40 +01:00
}
2018-12-27 10:59:01 +01:00
// Take stack_addr in advance to avoid many duplicate instructions
2019-06-11 16:30:47 +02:00
CPlace::for_addr(place.to_addr(fx), layout)
2018-12-25 16:47:33 +01:00
};
2018-12-28 15:18:17 +01:00
let prev_place = fx.local_map.insert(local, place);
debug_assert!(prev_place.is_none());
2018-12-25 16:47:33 +01:00
fx.local_map[&local]
}
2018-12-27 10:59:01 +01:00
fn cvalue_for_param<'a, 'tcx: 'a>(
fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
start_ebb: Ebb,
local: mir::Local,
local_field: Option<usize>,
arg_ty: Ty<'tcx>,
ssa_flags: crate::analyze::Flags,
) -> Option<CValue<'tcx>> {
2018-12-27 10:59:01 +01:00
let layout = fx.layout_of(arg_ty);
2019-06-16 12:54:37 +02:00
let pass_mode = get_pass_mode(fx.tcx, fx.layout_of(arg_ty));
if let PassMode::NoPass = pass_mode {
return None;
}
2019-06-16 12:54:37 +02:00
let clif_types = pass_mode.get_param_ty(fx);
let ebb_params = clif_types.map(|t| fx.bcx.append_ebb_param(start_ebb, t));
2018-12-28 17:07:40 +01:00
#[cfg(debug_assertions)]
2019-02-21 15:06:09 +01:00
add_arg_comment(
fx,
"arg",
local,
local_field,
2019-06-16 12:54:37 +02:00
ebb_params,
2019-02-21 15:06:09 +01:00
pass_mode,
ssa_flags,
arg_ty,
);
2018-12-28 17:07:40 +01:00
2018-12-27 10:59:01 +01:00
match pass_mode {
PassMode::NoPass => unreachable!(),
2019-06-16 12:54:37 +02:00
PassMode::ByVal(_) => Some(CValue::by_val(ebb_params.assert_single(), layout)),
PassMode::ByValPair(_, _) => {
let (a, b) = ebb_params.assert_pair();
Some(CValue::by_val_pair(a, b, layout))
}
PassMode::ByRef => Some(CValue::by_ref(ebb_params.assert_single(), layout)),
2018-12-25 16:47:33 +01:00
}
}
2018-08-14 20:31:16 +02:00
pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
start_ebb: Ebb,
) {
2018-08-09 10:46:56 +02:00
let ssa_analyzed = crate::analyze::analyze(fx);
2018-12-28 17:07:40 +01:00
#[cfg(debug_assertions)]
2018-12-26 11:15:42 +01:00
fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
2018-08-09 10:46:56 +02:00
2019-06-16 12:54:37 +02:00
let ret_layout = fx.return_layout();
let output_pass_mode = get_pass_mode(fx.tcx, fx.return_layout());
let ret_param = match output_pass_mode {
2019-06-16 12:54:37 +02:00
PassMode::NoPass | PassMode::ByVal(_) | PassMode::ByValPair(_, _) => None,
PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.pointer_type)),
};
2018-07-19 19:33:42 +02:00
2018-12-28 17:07:40 +01:00
#[cfg(debug_assertions)]
{
add_local_header_comment(fx);
2019-06-16 12:54:37 +02:00
let ret_param = match ret_param {
Some(param) => Single(param),
None => Empty,
};
2019-02-21 15:06:09 +01:00
add_arg_comment(
fx,
"ret",
RETURN_PLACE,
None,
ret_param,
output_pass_mode,
ssa_analyzed[&RETURN_PLACE],
ret_layout.ty,
);
2018-12-28 17:07:40 +01:00
}
2018-12-27 10:59:01 +01:00
// None means pass_mode == NoPass
2018-12-27 10:59:01 +01:00
enum ArgKind<'tcx> {
Normal(Option<CValue<'tcx>>),
Spread(Vec<Option<CValue<'tcx>>>),
}
2018-08-14 12:13:07 +02:00
let func_params = fx
.mir
.args_iter()
.map(|local| {
let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
// Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
if Some(local) == fx.mir.spread_arg {
// This argument (e.g. the last argument in the "rust-call" ABI)
// is a tuple that was spread at the ABI level and now we have
// to reconstruct it into a tuple local variable, from multiple
// individual function arguments.
let tupled_arg_tys = match arg_ty.sty {
ty::Tuple(ref tys) => tys,
2018-08-14 12:13:07 +02:00
_ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
};
2018-12-27 10:59:01 +01:00
let mut params = Vec::new();
for (i, arg_ty) in tupled_arg_tys.types().enumerate() {
2019-02-21 15:06:09 +01:00
let param = cvalue_for_param(
fx,
start_ebb,
local,
Some(i),
arg_ty,
ssa_analyzed[&local],
);
2018-12-27 10:59:01 +01:00
params.push(param);
2018-08-14 12:13:07 +02:00
}
2018-12-27 10:59:01 +01:00
(local, ArgKind::Spread(params), arg_ty)
2018-08-14 12:13:07 +02:00
} else {
2019-02-21 15:06:09 +01:00
let param =
cvalue_for_param(fx, start_ebb, local, None, arg_ty, ssa_analyzed[&local]);
(local, ArgKind::Normal(param), arg_ty)
}
2018-10-10 19:07:13 +02:00
})
.collect::<Vec<(Local, ArgKind, Ty)>>();
2018-08-14 18:52:43 +02:00
fx.bcx.switch_to_block(start_ebb);
match output_pass_mode {
PassMode::NoPass => {
2019-02-21 15:06:09 +01:00
fx.local_map
2019-06-11 15:32:30 +02:00
.insert(RETURN_PLACE, CPlace::no_place(ret_layout));
}
2019-06-16 12:54:37 +02:00
PassMode::ByVal(_) | PassMode::ByValPair(_, _) => {
let is_ssa = !ssa_analyzed
.get(&RETURN_PLACE)
.unwrap()
.contains(crate::analyze::Flags::NOT_SSA);
local_place(fx, RETURN_PLACE, ret_layout, is_ssa);
}
PassMode::ByRef => {
2018-08-22 15:38:10 +02:00
fx.local_map.insert(
RETURN_PLACE,
2019-06-11 16:30:47 +02:00
CPlace::for_addr(ret_param.unwrap(), ret_layout),
2018-08-22 15:38:10 +02:00
);
}
}
for (local, arg_kind, ty) in func_params {
let layout = fx.layout_of(ty);
2018-08-09 10:46:56 +02:00
2018-12-25 16:47:33 +01:00
let is_ssa = !ssa_analyzed
.get(&local)
.unwrap()
.contains(crate::analyze::Flags::NOT_SSA);
2018-12-26 11:15:42 +01:00
let place = local_place(fx, local, layout, is_ssa);
match arg_kind {
2018-12-27 10:59:01 +01:00
ArgKind::Normal(param) => {
if let Some(param) = param {
place.write_cvalue(fx, param);
}
}
2018-12-27 10:59:01 +01:00
ArgKind::Spread(params) => {
for (i, param) in params.into_iter().enumerate() {
if let Some(param) = param {
place
.place_field(fx, mir::Field::new(i))
.write_cvalue(fx, param);
}
}
}
2018-07-19 19:33:42 +02:00
}
}
for local in fx.mir.vars_and_temps_iter() {
let ty = fx.mir.local_decls[local].ty;
let layout = fx.layout_of(ty);
2018-08-09 10:46:56 +02:00
2018-12-26 11:15:42 +01:00
let is_ssa = !ssa_analyzed
2018-08-09 11:25:14 +02:00
.get(&local)
.unwrap()
2018-12-26 11:15:42 +01:00
.contains(crate::analyze::Flags::NOT_SSA);
2018-08-09 10:46:56 +02:00
2018-12-26 11:15:42 +01:00
local_place(fx, local, layout, is_ssa);
2018-07-19 19:33:42 +02:00
}
2018-08-14 18:52:43 +02:00
fx.bcx
.ins()
.jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
2018-07-19 19:33:42 +02:00
}
2018-09-11 19:27:57 +02:00
pub fn codegen_terminator_call<'a, 'tcx: 'a>(
2018-08-14 20:31:16 +02:00
fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
2018-07-19 19:33:42 +02:00
func: &Operand<'tcx>,
args: &[Operand<'tcx>],
destination: &Option<(Place<'tcx>, BasicBlock)>,
2018-07-20 13:51:34 +02:00
) {
let fn_ty = fx.monomorphize(&func.ty(fx.mir, fx.tcx));
let sig = fx.tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &fn_ty.fn_sig(fx.tcx));
2018-07-20 13:38:49 +02:00
// Unpack arguments tuple for closures
let args = if sig.abi == Abi::RustCall {
assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
let self_arg = trans_operand(fx, &args[0]);
let pack_arg = trans_operand(fx, &args[1]);
2018-07-20 13:38:49 +02:00
let mut args = Vec::new();
args.push(self_arg);
match pack_arg.layout().ty.sty {
ty::Tuple(ref tupled_arguments) => {
2018-07-20 13:38:49 +02:00
for (i, _) in tupled_arguments.iter().enumerate() {
args.push(pack_arg.value_field(fx, mir::Field::new(i)));
}
}
2018-07-20 13:38:49 +02:00
_ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
}
args
} else {
args.into_iter()
.map(|arg| trans_operand(fx, arg))
2018-07-20 13:38:49 +02:00
.collect::<Vec<_>>()
};
2018-08-11 13:59:34 +02:00
let destination = destination
.as_ref()
2018-09-11 19:27:57 +02:00
.map(|&(ref place, bb)| (trans_place(fx, place), bb));
if let ty::FnDef(def_id, substs) = fn_ty.sty {
2019-02-21 15:06:09 +01:00
let instance =
ty::Instance::resolve(fx.tcx, ty::ParamEnv::reveal_all(), def_id, substs).unwrap();
match instance.def {
InstanceDef::Intrinsic(_) => {
crate::intrinsics::codegen_intrinsic_call(fx, def_id, substs, args, destination);
return;
}
InstanceDef::DropGlue(_, None) => {
// empty drop glue - a nop.
let (_, dest) = destination.expect("Non terminating drop_in_place_real???");
let ret_ebb = fx.get_ebb(dest);
fx.bcx.ins().jump(ret_ebb, &[]);
return;
}
_ => {}
2018-09-11 19:27:57 +02:00
}
}
codegen_call_inner(
fx,
Some(func),
fn_ty,
args,
destination.map(|(place, _)| place),
);
if let Some((_, dest)) = destination {
let ret_ebb = fx.get_ebb(dest);
fx.bcx.ins().jump(ret_ebb, &[]);
} else {
2019-03-23 13:06:35 +01:00
trap_unreachable(fx, "[corruption] Diverging function returned");
}
2018-09-11 19:27:57 +02:00
}
2019-06-16 15:57:53 +02:00
fn codegen_call_inner<'a, 'tcx: 'a>(
2018-09-11 19:27:57 +02:00
fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
func: Option<&Operand<'tcx>>,
fn_ty: Ty<'tcx>,
args: Vec<CValue<'tcx>>,
ret_place: Option<CPlace<'tcx>>,
) {
let fn_sig = fx.tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &fn_ty.fn_sig(fx.tcx));
2019-01-02 12:20:32 +01:00
let ret_layout = fx.layout_of(fn_sig.output());
2019-06-16 12:54:37 +02:00
let output_pass_mode = get_pass_mode(fx.tcx, fx.layout_of(fn_sig.output()));
let return_ptr = match output_pass_mode {
PassMode::NoPass => None,
2018-09-11 19:27:57 +02:00
PassMode::ByRef => match ret_place {
2019-02-04 19:27:58 +01:00
Some(ret_place) => Some(ret_place.to_addr(fx)),
None => Some(fx.bcx.ins().iconst(fx.pointer_type, 43)),
},
2019-06-16 12:54:37 +02:00
PassMode::ByVal(_) | PassMode::ByValPair(_, _) => None,
};
2018-09-08 18:00:06 +02:00
let instance = match fn_ty.sty {
ty::FnDef(def_id, substs) => {
2018-09-08 18:00:06 +02:00
Some(Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap())
2018-08-19 10:50:39 +02:00
}
2018-09-08 18:00:06 +02:00
_ => None,
};
2019-06-16 12:54:37 +02:00
// | indirect call target
// | | the first argument to be passed
// v v v virtual calls are special cased below
let (func_ref, first_arg, is_virtual_call) = match instance {
// Trait object call
Some(Instance {
2018-09-08 18:00:06 +02:00
def: InstanceDef::Virtual(_, idx),
..
}) => {
2019-06-16 14:47:01 +02:00
#[cfg(debug_assertions)]
{
let nop_inst = fx.bcx.ins().nop();
fx.add_comment(
nop_inst,
format!("virtual call; self arg pass mode: {:?}", get_pass_mode(fx.tcx, args[0].layout())),
);
}
2018-09-08 18:00:06 +02:00
let (ptr, method) = crate::vtable::get_ptr_and_method_ref(fx, args[0], idx);
2019-06-16 12:54:37 +02:00
(Some(method), Single(ptr), true)
}
2018-09-08 18:00:06 +02:00
// Normal call
2019-06-16 12:54:37 +02:00
Some(_) => (None, args.get(0).map(|arg| adjust_arg_for_abi(fx, *arg)).unwrap_or(Empty), false),
// Indirect call
None => {
2019-06-16 14:47:01 +02:00
#[cfg(debug_assertions)]
{
let nop_inst = fx.bcx.ins().nop();
fx.add_comment(nop_inst, "indirect call");
}
2019-02-21 15:06:09 +01:00
let func = trans_operand(fx, func.expect("indirect call without func Operand"))
.load_scalar(fx);
(
Some(func),
2019-06-16 12:54:37 +02:00
args.get(0).map(|arg| adjust_arg_for_abi(fx, *arg)).unwrap_or(Empty),
false,
2019-02-21 15:06:09 +01:00
)
2018-10-10 19:07:13 +02:00
}
2018-09-08 18:00:06 +02:00
};
let call_args: Vec<Value> = return_ptr
.into_iter()
2019-06-16 12:54:37 +02:00
.chain(first_arg.into_iter())
2018-09-08 18:00:06 +02:00
.chain(
args.into_iter()
.skip(1)
2019-06-16 12:54:37 +02:00
.map(|arg| adjust_arg_for_abi(fx, arg).into_iter())
.flatten(),
2018-10-10 19:07:13 +02:00
)
.collect::<Vec<_>>();
2018-09-08 18:00:06 +02:00
let call_inst = if let Some(func_ref) = func_ref {
2019-02-21 15:06:09 +01:00
let sig = fx
.bcx
2019-06-16 12:54:37 +02:00
.import_signature(clif_sig_from_fn_sig(fx.tcx, fn_sig, is_virtual_call));
2018-09-08 18:00:06 +02:00
fx.bcx.ins().call_indirect(sig, func_ref, &call_args)
} else {
let func_ref = fx.get_function_ref(instance.expect("non-indirect call on non-FnDef type"));
fx.bcx.ins().call(func_ref, &call_args)
};
2019-02-11 19:18:52 +01:00
// FIXME find a cleaner way to support varargs
if fn_sig.c_variadic {
2019-02-11 19:18:52 +01:00
if fn_sig.abi != Abi::C {
unimpl!("Variadic call for non-C abi {:?}", fn_sig.abi);
}
let sig_ref = fx.bcx.func.dfg.call_signature(call_inst).unwrap();
2019-02-21 15:06:09 +01:00
let abi_params = call_args
.into_iter()
.map(|arg| {
let ty = fx.bcx.func.dfg.value_type(arg);
if !ty.is_int() {
// FIXME set %al to upperbound on float args once floats are supported
unimpl!("Non int ty {:?} for variadic call", ty);
}
AbiParam::new(ty)
})
.collect::<Vec<AbiParam>>();
2019-02-11 19:18:52 +01:00
fx.bcx.func.dfg.signatures[sig_ref].params = abi_params;
}
match output_pass_mode {
PassMode::NoPass => {}
PassMode::ByVal(_) => {
2018-09-11 19:27:57 +02:00
if let Some(ret_place) = ret_place {
let ret_val = fx.bcx.inst_results(call_inst)[0];
2019-06-11 15:32:30 +02:00
ret_place.write_cvalue(fx, CValue::by_val(ret_val, ret_layout));
}
}
2019-06-16 12:54:37 +02:00
PassMode::ByValPair(_, _) => {
if let Some(ret_place) = ret_place {
let ret_val_a = fx.bcx.inst_results(call_inst)[0];
let ret_val_b = fx.bcx.inst_results(call_inst)[1];
ret_place.write_cvalue(fx, CValue::by_val_pair(ret_val_a, ret_val_b, ret_layout));
}
}
PassMode::ByRef => {}
2018-07-20 13:51:34 +02:00
}
2018-07-19 19:33:42 +02:00
}
2018-08-10 19:20:13 +02:00
2019-02-07 20:45:15 +01:00
pub fn codegen_drop<'a, 'tcx: 'a>(
fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
drop_place: CPlace<'tcx>,
) {
2019-06-16 15:57:53 +02:00
let ty = drop_place.layout().ty;
let drop_fn = Instance::resolve_drop_in_place(fx.tcx, ty);
2019-02-07 20:45:15 +01:00
2019-06-16 15:57:53 +02:00
if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
// we don't actually need to drop anything
} else {
let drop_fn_ty = drop_fn.ty(fx.tcx);
match ty.sty {
ty::Dynamic(..) => {
let (ptr, vtable) = drop_place.to_addr_maybe_unsized(fx);
let drop_fn = crate::vtable::drop_fn_of_obj(fx, vtable.unwrap());
2019-02-07 20:45:15 +01:00
2019-06-16 15:57:53 +02:00
let fn_sig = fx.tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &drop_fn_ty.fn_sig(fx.tcx));
2019-02-07 20:45:15 +01:00
2019-06-16 15:57:53 +02:00
assert_eq!(fn_sig.output(), fx.tcx.mk_unit());
let sig = fx
.bcx
.import_signature(clif_sig_from_fn_sig(fx.tcx, fn_sig, true));
fx.bcx.ins().call_indirect(sig, drop_fn, &[ptr]);
}
_ => {
let arg_place = CPlace::new_stack_slot(
fx,
fx.tcx.mk_ref(
&ty::RegionKind::ReErased,
TypeAndMut {
ty,
mutbl: crate::rustc::hir::Mutability::MutMutable,
},
),
);
drop_place.write_place_ref(fx, arg_place);
let arg_value = arg_place.to_cvalue(fx);
crate::abi::codegen_call_inner(
fx,
None,
drop_fn_ty,
vec![arg_value],
None,
);
}
}
}
2019-02-07 20:45:15 +01:00
}
2018-08-14 20:31:16 +02:00
pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
2019-06-16 12:54:37 +02:00
match get_pass_mode(fx.tcx, fx.return_layout()) {
PassMode::NoPass | PassMode::ByRef => {
fx.bcx.ins().return_(&[]);
2018-08-11 13:59:34 +02:00
}
PassMode::ByVal(_) => {
let place = fx.get_local_place(RETURN_PLACE);
let ret_val = place.to_cvalue(fx).load_scalar(fx);
fx.bcx.ins().return_(&[ret_val]);
}
2019-06-16 12:54:37 +02:00
PassMode::ByValPair(_, _) => {
let place = fx.get_local_place(RETURN_PLACE);
let (ret_val_a, ret_val_b) = place.to_cvalue(fx).load_scalar_pair(fx);
fx.bcx.ins().return_(&[ret_val_a, ret_val_b]);
}
}
2018-08-11 11:01:48 +02:00
}