1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Handles translation of callees as well as other call-related
12 //! things. Callees are a superset of normal rust values and sometimes
13 //! have different representations. In particular, top-level fn items
14 //! and methods are represented as just a fn ptr and not a full
17 pub use self::AutorefArg::*;
18 pub use self::CalleeData::*;
19 pub use self::CallArgs::*;
21 use arena::TypedArena;
24 use llvm::{self, ValueRef, get_params};
26 use middle::def_id::{DefId, LOCAL_CRATE};
27 use middle::infer::normalize_associated_type;
29 use middle::subst::{Subst, Substs};
30 use rustc::front::map as hir_map;
37 use trans::cleanup::CleanupMethods;
38 use trans::common::{self, Block, Result, NodeIdAndSpan, ExprId, CrateContext,
39 ExprOrMethodCall, FunctionContext, MethodCallKey};
42 use trans::debuginfo::{DebugLoc, ToDebugLoc};
50 use trans::monomorphize;
51 use trans::type_::Type;
53 use middle::ty::{self, Ty, HasTypeFlags, RegionEscape};
54 use middle::ty::MethodCall;
57 use syntax::abi as synabi;
61 #[derive(Copy, Clone)]
62 pub struct MethodData {
67 pub enum CalleeData<'tcx> {
68 // Constructor for enum variant/tuple-like-struct
70 NamedTupleConstructor(ty::Disr),
72 // Represents a (possibly monomorphized) top-level fn item or method
73 // item. Note that this is just the fn-ptr and is not a Rust closure
74 // value (which is a pair).
75 Fn(/* llfn */ ValueRef),
77 Intrinsic(ast::NodeId, subst::Substs<'tcx>),
82 pub struct Callee<'blk, 'tcx: 'blk> {
83 pub bcx: Block<'blk, 'tcx>,
84 pub data: CalleeData<'tcx>,
88 fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &hir::Expr)
89 -> Callee<'blk, 'tcx> {
90 let _icx = push_ctxt("trans_callee");
91 debug!("callee::trans(expr={:?})", expr);
93 // pick out special kinds of expressions that can be called:
95 hir::ExprPath(..) => {
96 return trans_def(bcx, bcx.def(expr.id), expr);
101 // any other expressions are closures:
102 return datum_callee(bcx, expr);
104 fn datum_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &hir::Expr)
105 -> Callee<'blk, 'tcx> {
106 let DatumBlock { bcx, datum, .. } = expr::trans(bcx, expr);
108 ty::TyBareFn(..) => {
112 data: Fn(datum.to_llscalarish(bcx))
116 bcx.tcx().sess.span_bug(
118 &format!("type of callee is neither bare-fn nor closure: {}",
124 fn fn_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, datum: Datum<'tcx, Rvalue>)
125 -> Callee<'blk, 'tcx> {
133 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
135 ref_expr: &hir::Expr)
136 -> Callee<'blk, 'tcx> {
137 debug!("trans_def(def={:?}, ref_expr={:?})", def, ref_expr);
138 let expr_ty = common::node_id_type(bcx, ref_expr.id);
140 def::DefFn(did, _) if {
141 let maybe_def_id = inline::get_local_instance(bcx.ccx(), did);
142 let maybe_ast_node = maybe_def_id.and_then(|def_id| bcx.tcx().map
144 match maybe_ast_node {
145 Some(hir_map::NodeStructCtor(_)) => true,
151 data: NamedTupleConstructor(0),
155 def::DefFn(did, _) if match expr_ty.sty {
156 ty::TyBareFn(_, ref f) => f.abi == synabi::RustIntrinsic ||
157 f.abi == synabi::PlatformIntrinsic,
160 let substs = common::node_id_substs(bcx.ccx(),
162 bcx.fcx.param_substs);
163 let def_id = inline::maybe_instantiate_inline(bcx.ccx(), did);
164 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs), ty: expr_ty }
166 def::DefFn(did, _) => {
167 fn_callee(bcx, trans_fn_ref(bcx.ccx(), did, ExprId(ref_expr.id),
168 bcx.fcx.param_substs))
170 def::DefMethod(meth_did) => {
171 let method_item = bcx.tcx().impl_or_trait_item(meth_did);
172 let fn_datum = match method_item.container() {
173 ty::ImplContainer(_) => {
174 trans_fn_ref(bcx.ccx(), meth_did,
176 bcx.fcx.param_substs)
178 ty::TraitContainer(trait_did) => {
179 meth::trans_static_method_callee(bcx.ccx(),
183 bcx.fcx.param_substs)
186 fn_callee(bcx, fn_datum)
188 def::DefVariant(tid, vid, _) => {
189 let vinfo = bcx.tcx().lookup_adt_def(tid).variant_with_id(vid);
190 assert_eq!(vinfo.kind(), ty::VariantKind::Tuple);
194 data: NamedTupleConstructor(vinfo.disr_val),
198 def::DefStruct(_) => {
201 data: NamedTupleConstructor(0),
207 def::DefAssociatedConst(..) |
209 def::DefUpvar(..) => {
210 datum_callee(bcx, ref_expr)
212 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
213 def::DefTy(..) | def::DefPrimTy(..) | def::DefAssociatedTy(..) |
214 def::DefUse(..) | def::DefRegion(..) | def::DefLabel(..) |
215 def::DefTyParam(..) | def::DefSelfTy(..) => {
216 bcx.tcx().sess.span_bug(
218 &format!("cannot translate def {:?} \
219 to a callable thing!", def));
225 /// Translates a reference (with id `ref_id`) to the fn/method with id `def_id` into a function
226 /// pointer. This may require monomorphization or inlining.
227 pub fn trans_fn_ref<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
229 node: ExprOrMethodCall,
230 param_substs: &'tcx subst::Substs<'tcx>)
231 -> Datum<'tcx, Rvalue> {
232 let _icx = push_ctxt("trans_fn_ref");
234 let substs = common::node_id_substs(ccx, node, param_substs);
235 debug!("trans_fn_ref(def_id={:?}, node={:?}, substs={:?})",
239 trans_fn_ref_with_substs(ccx, def_id, node, param_substs, substs)
242 /// Translates an adapter that implements the `Fn` trait for a fn
243 /// pointer. This is basically the equivalent of something like:
246 /// impl<'a> Fn(&'a int) -> &'a int for fn(&int) -> &int {
247 /// extern "rust-abi" fn call(&self, args: (&'a int,)) -> &'a int {
253 /// but for the bare function type given.
254 pub fn trans_fn_pointer_shim<'a, 'tcx>(
255 ccx: &'a CrateContext<'a, 'tcx>,
256 closure_kind: ty::ClosureKind,
257 bare_fn_ty: Ty<'tcx>)
260 let _icx = push_ctxt("trans_fn_pointer_shim");
263 // Normalize the type for better caching.
264 let bare_fn_ty = tcx.erase_regions(&bare_fn_ty);
266 // If this is an impl of `Fn` or `FnMut` trait, the receiver is `&self`.
267 let is_by_ref = match closure_kind {
268 ty::FnClosureKind | ty::FnMutClosureKind => true,
269 ty::FnOnceClosureKind => false,
271 let bare_fn_ty_maybe_ref = if is_by_ref {
272 tcx.mk_imm_ref(tcx.mk_region(ty::ReStatic), bare_fn_ty)
277 // Check if we already trans'd this shim.
278 match ccx.fn_pointer_shims().borrow().get(&bare_fn_ty_maybe_ref) {
279 Some(&llval) => { return llval; }
283 debug!("trans_fn_pointer_shim(bare_fn_ty={:?})",
286 // Construct the "tuply" version of `bare_fn_ty`. It takes two arguments: `self`,
287 // which is the fn pointer, and `args`, which is the arguments tuple.
288 let (opt_def_id, sig) =
289 match bare_fn_ty.sty {
290 ty::TyBareFn(opt_def_id,
291 &ty::BareFnTy { unsafety: hir::Unsafety::Normal,
298 tcx.sess.bug(&format!("trans_fn_pointer_shim invoked on invalid type: {}",
302 let sig = tcx.erase_late_bound_regions(sig);
303 let tuple_input_ty = tcx.mk_tup(sig.inputs.to_vec());
304 let tuple_fn_ty = tcx.mk_fn(opt_def_id,
305 tcx.mk_bare_fn(ty::BareFnTy {
306 unsafety: hir::Unsafety::Normal,
307 abi: synabi::RustCall,
308 sig: ty::Binder(ty::FnSig {
309 inputs: vec![bare_fn_ty_maybe_ref,
314 debug!("tuple_fn_ty: {:?}", tuple_fn_ty);
317 let function_name = link::mangle_internal_name_by_type_and_seq(ccx, bare_fn_ty,
319 let llfn = declare::declare_internal_rust_fn(ccx, &function_name[..], tuple_fn_ty);
322 let empty_substs = tcx.mk_substs(Substs::trans_empty());
323 let (block_arena, fcx): (TypedArena<_>, FunctionContext);
324 block_arena = TypedArena::new();
325 fcx = new_fn_ctxt(ccx,
333 let mut bcx = init_function(&fcx, false, sig.output);
335 let llargs = get_params(fcx.llfn);
337 let self_idx = fcx.arg_offset();
338 // the first argument (`self`) will be ptr to the the fn pointer
339 let llfnpointer = if is_by_ref {
340 Load(bcx, llargs[self_idx])
345 assert!(!fcx.needs_ret_allocas);
347 let dest = fcx.llretslotptr.get().map(|_|
348 expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot"))
351 bcx = trans_call_inner(bcx, DebugLoc::None, |bcx, _| {
354 data: Fn(llfnpointer),
357 }, ArgVals(&llargs[(self_idx + 1)..]), dest).bcx;
359 finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
361 ccx.fn_pointer_shims().borrow_mut().insert(bare_fn_ty_maybe_ref, llfn);
366 /// Translates a reference to a fn/method item, monomorphizing and
367 /// inlining as it goes.
371 /// - `ccx`: the crate context
372 /// - `def_id`: def id of the fn or method item being referenced
373 /// - `node`: node id of the reference to the fn/method, if applicable.
374 /// This parameter may be zero; but, if so, the resulting value may not
375 /// have the right type, so it must be cast before being used.
376 /// - `param_substs`: if the `node` is in a polymorphic function, these
377 /// are the substitutions required to monomorphize its type
378 /// - `substs`: values for each of the fn/method's parameters
379 pub fn trans_fn_ref_with_substs<'a, 'tcx>(
380 ccx: &CrateContext<'a, 'tcx>,
382 node: ExprOrMethodCall,
383 param_substs: &'tcx subst::Substs<'tcx>,
384 substs: subst::Substs<'tcx>)
385 -> Datum<'tcx, Rvalue>
387 let _icx = push_ctxt("trans_fn_ref_with_substs");
390 debug!("trans_fn_ref_with_substs(def_id={:?}, node={:?}, \
391 param_substs={:?}, substs={:?})",
397 assert!(!substs.types.needs_infer());
398 assert!(!substs.types.has_escaping_regions());
399 let substs = substs.erase_regions();
401 // Load the info for the appropriate trait if necessary.
402 match tcx.trait_of_item(def_id) {
405 tcx.populate_implementations_for_trait_if_necessary(trait_id)
409 // We need to do a bunch of special handling for default methods.
410 // We need to modify the def_id and our substs in order to monomorphize
412 let (is_default, def_id, substs) = match tcx.provided_source(def_id) {
414 (false, def_id, tcx.mk_substs(substs))
417 // There are two relevant substitutions when compiling
418 // default methods. First, there is the substitution for
419 // the type parameters of the impl we are using and the
420 // method we are calling. This substitution is the substs
421 // argument we already have.
422 // In order to compile a default method, though, we need
423 // to consider another substitution: the substitution for
424 // the type parameters on trait; the impl we are using
425 // implements the trait at some particular type
426 // parameters, and we need to substitute for those first.
427 // So, what we need to do is find this substitution and
428 // compose it with the one we already have.
430 let impl_id = tcx.impl_or_trait_item(def_id).container()
432 let impl_or_trait_item = tcx.impl_or_trait_item(source_id);
433 match impl_or_trait_item {
434 ty::MethodTraitItem(method) => {
435 let trait_ref = tcx.impl_trait_ref(impl_id).unwrap();
437 // Compute the first substitution
439 tcx.make_substs_for_receiver_types(&trait_ref, &*method)
443 let new_substs = tcx.mk_substs(first_subst.subst(tcx, &substs));
445 debug!("trans_fn_with_vtables - default method: \
446 substs = {:?}, trait_subst = {:?}, \
447 first_subst = {:?}, new_subst = {:?}",
448 substs, trait_ref.substs,
449 first_subst, new_substs);
451 (true, source_id, new_substs)
454 tcx.sess.bug("trans_fn_ref_with_vtables() tried \
455 to translate a non-method?!")
461 // Check whether this fn has an inlined copy and, if so, redirect
462 // def_id to the local id of the inlined copy.
463 let def_id = inline::maybe_instantiate_inline(ccx, def_id);
465 // We must monomorphise if the fn has type parameters, is a default method,
466 // or is a named tuple constructor.
467 let must_monomorphise = if !substs.types.is_empty() || is_default {
469 } else if def_id.is_local() {
470 let map_node = session::expect(
472 tcx.map.find(def_id.node),
473 || "local item should be in ast map".to_string());
476 hir_map::NodeVariant(v) => match v.node.kind {
477 hir::TupleVariantKind(ref args) => !args.is_empty(),
480 hir_map::NodeStructCtor(_) => true,
487 debug!("trans_fn_ref_with_substs({:?}) must_monomorphise: {}",
488 def_id, must_monomorphise);
490 // Create a monomorphic version of generic functions
491 if must_monomorphise {
492 // Should be either intra-crate or inlined.
493 assert_eq!(def_id.krate, LOCAL_CRATE);
495 let opt_ref_id = match node {
496 ExprId(id) => if id != 0 { Some(id) } else { None },
497 MethodCallKey(_) => None,
500 let (val, fn_ty, must_cast) =
501 monomorphize::monomorphic_fn(ccx, def_id, substs, opt_ref_id);
502 if must_cast && node != ExprId(0) {
503 // Monotype of the REFERENCE to the function (type params
505 let ref_ty = match node {
506 ExprId(id) => tcx.node_id_to_type(id),
507 MethodCallKey(method_call) => {
508 tcx.tables.borrow().method_map[&method_call].ty
511 let ref_ty = monomorphize::apply_param_substs(tcx,
514 let llptrty = type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to();
515 if llptrty != common::val_ty(val) {
516 let val = consts::ptrcast(val, llptrty);
517 return Datum::new(val, ref_ty, Rvalue::new(ByValue));
520 return Datum::new(val, fn_ty, Rvalue::new(ByValue));
523 // Type scheme of the function item (may have type params)
524 let fn_type_scheme = tcx.lookup_item_type(def_id);
525 let fn_type = normalize_associated_type(tcx, &fn_type_scheme.ty);
527 // Find the actual function pointer.
529 if def_id.is_local() {
530 // Internal reference.
531 get_item_val(ccx, def_id.node)
533 // External reference.
534 trans_external_path(ccx, def_id, fn_type)
538 // This is subtle and surprising, but sometimes we have to bitcast
539 // the resulting fn pointer. The reason has to do with external
540 // functions. If you have two crates that both bind the same C
541 // library, they may not use precisely the same types: for
542 // example, they will probably each declare their own structs,
543 // which are distinct types from LLVM's point of view (nominal
546 // Now, if those two crates are linked into an application, and
547 // they contain inlined code, you can wind up with a situation
548 // where both of those functions wind up being loaded into this
549 // application simultaneously. In that case, the same function
550 // (from LLVM's point of view) requires two types. But of course
551 // LLVM won't allow one function to have two types.
553 // What we currently do, therefore, is declare the function with
554 // one of the two types (whichever happens to come first) and then
555 // bitcast as needed when the function is referenced to make sure
556 // it has the type we expect.
558 // This can occur on either a crate-local or crate-external
559 // reference. It also occurs when testing libcore and in some
560 // other weird situations. Annoying.
561 let llty = type_of::type_of_fn_from_ty(ccx, fn_type);
562 let llptrty = llty.ptr_to();
563 if common::val_ty(val) != llptrty {
564 debug!("trans_fn_ref_with_vtables(): casting pointer!");
565 val = consts::ptrcast(val, llptrty);
567 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
570 Datum::new(val, fn_type, Rvalue::new(ByValue))
573 // ______________________________________________________________________
576 pub fn trans_call<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
577 call_expr: &hir::Expr,
579 args: CallArgs<'a, 'tcx>,
581 -> Block<'blk, 'tcx> {
582 let _icx = push_ctxt("trans_call");
583 trans_call_inner(bcx,
584 call_expr.debug_loc(),
585 |bcx, _| trans(bcx, f),
590 pub fn trans_method_call<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
591 call_expr: &hir::Expr,
593 args: CallArgs<'a, 'tcx>,
595 -> Block<'blk, 'tcx> {
596 let _icx = push_ctxt("trans_method_call");
597 debug!("trans_method_call(call_expr={:?})", call_expr);
598 let method_call = MethodCall::expr(call_expr.id);
601 call_expr.debug_loc(),
602 |cx, arg_cleanup_scope| {
603 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
609 pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
612 dest: Option<expr::Dest>,
614 -> Result<'blk, 'tcx> {
615 callee::trans_call_inner(bcx, debug_loc, |bcx, _| {
616 let datum = trans_fn_ref_with_substs(bcx.ccx(),
619 bcx.fcx.param_substs,
620 subst::Substs::trans_empty());
626 }, ArgVals(args), dest)
629 /// This behemoth of a function translates function calls. Unfortunately, in
630 /// order to generate more efficient LLVM output at -O0, it has quite a complex
631 /// signature (refactoring this into two functions seems like a good idea).
633 /// In particular, for lang items, it is invoked with a dest of None, and in
634 /// that case the return value contains the result of the fn. The lang item must
635 /// not return a structural type or else all heck breaks loose.
637 /// For non-lang items, `dest` is always Some, and hence the result is written
638 /// into memory somewhere. Nonetheless we return the actual return value of the
640 pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
643 args: CallArgs<'a, 'tcx>,
644 dest: Option<expr::Dest>)
645 -> Result<'blk, 'tcx> where
646 F: FnOnce(Block<'blk, 'tcx>, cleanup::ScopeId) -> Callee<'blk, 'tcx>,
648 // Introduce a temporary cleanup scope that will contain cleanups
649 // for the arguments while they are being evaluated. The purpose
650 // this cleanup is to ensure that, should a panic occur while
651 // evaluating argument N, the values for arguments 0...N-1 are all
652 // cleaned up. If no panic occurs, the values are handed off to
653 // the callee, and hence none of the cleanups in this temporary
654 // scope will ever execute.
657 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
659 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
660 let mut bcx = callee.bcx;
662 let (abi, ret_ty) = match callee.ty.sty {
663 ty::TyBareFn(_, ref f) => {
664 let output = bcx.tcx().erase_late_bound_regions(&f.sig.output());
667 _ => panic!("expected bare rust fn or closure in trans_call_inner")
670 let (llfn, llself) = match callee.data {
675 (d.llfn, Some(d.llself))
677 Intrinsic(node, substs) => {
678 assert!(abi == synabi::RustIntrinsic || abi == synabi::PlatformIntrinsic);
679 assert!(dest.is_some());
681 let call_info = match debug_loc {
682 DebugLoc::At(id, span) => NodeIdAndSpan { id: id, span: span },
684 bcx.sess().bug("No call info for intrinsic call?")
688 return intrinsic::trans_intrinsic_call(bcx, node, callee.ty,
689 arg_cleanup_scope, args,
690 dest.unwrap(), substs,
693 NamedTupleConstructor(disr) => {
694 assert!(dest.is_some());
695 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
697 return base::trans_named_tuple_constructor(bcx,
706 // Intrinsics should not become actual functions.
707 // We trans them in place in `trans_intrinsic_call`
708 assert!(abi != synabi::RustIntrinsic && abi != synabi::PlatformIntrinsic);
710 let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
712 // Generate a location to store the result. If the user does
713 // not care about the result, just make a stack slot.
714 let opt_llretslot = dest.and_then(|dest| match dest {
715 expr::SaveIn(dst) => Some(dst),
717 let ret_ty = match ret_ty {
718 ty::FnConverging(ret_ty) => ret_ty,
719 ty::FnDiverging => ccx.tcx().mk_nil()
722 type_of::return_uses_outptr(ccx, ret_ty) ||
723 bcx.fcx.type_needs_drop(ret_ty) {
724 // Push the out-pointer if we use an out-pointer for this
725 // return type, otherwise push "undef".
726 if common::type_is_zero_size(ccx, ret_ty) {
727 let llty = type_of::type_of(ccx, ret_ty);
728 Some(common::C_undef(llty.ptr_to()))
730 let llresult = alloc_ty(bcx, ret_ty, "__llret");
731 call_lifetime_start(bcx, llresult);
740 let mut llresult = unsafe {
741 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
744 // The code below invokes the function, using either the Rust
745 // conventions (if it is a rust fn) or the native conventions
746 // (otherwise). The important part is that, when all is said
747 // and done, either the return value of the function will have been
748 // written in opt_llretslot (if it is Some) or `llresult` will be
749 // set appropriately (otherwise).
751 let mut llargs = Vec::new();
753 if let (ty::FnConverging(ret_ty), Some(mut llretslot)) = (ret_ty, opt_llretslot) {
754 if type_of::return_uses_outptr(ccx, ret_ty) {
755 let llformal_ret_ty = type_of::type_of(ccx, ret_ty).ptr_to();
756 let llret_ty = common::val_ty(llretslot);
757 if llformal_ret_ty != llret_ty {
758 // this could happen due to e.g. subtyping
759 debug!("casting actual return type ({}) to match formal ({})",
760 bcx.llty_str(llret_ty), bcx.llty_str(llformal_ret_ty));
761 llretslot = PointerCast(bcx, llretslot, llformal_ret_ty);
763 llargs.push(llretslot);
767 // Push a trait object's self.
768 if let Some(llself) = llself {
772 // Push the arguments.
773 bcx = trans_args(bcx,
777 cleanup::CustomScope(arg_cleanup_scope),
781 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
783 // Invoke the actual rust fn and update bcx/llresult.
784 let (llret, b) = base::invoke(bcx,
792 // If the Rust convention for this type is return via
793 // the return value, copy it into llretslot.
794 match (opt_llretslot, ret_ty) {
795 (Some(llretslot), ty::FnConverging(ret_ty)) => {
796 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
797 !common::type_is_zero_size(bcx.ccx(), ret_ty)
799 store_ty(bcx, llret, llretslot, ret_ty)
805 // Lang items are the only case where dest is None, and
806 // they are always Rust fns.
807 assert!(dest.is_some());
809 let mut llargs = Vec::new();
810 let arg_tys = match args {
811 ArgExprs(a) => a.iter().map(|x| common::expr_ty_adjusted(bcx, &**x)).collect(),
812 _ => panic!("expected arg exprs.")
814 bcx = trans_args(bcx,
818 cleanup::CustomScope(arg_cleanup_scope),
821 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
823 bcx = foreign::trans_native_call(bcx,
826 opt_llretslot.unwrap(),
832 fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_cleanup_scope);
834 // If the caller doesn't care about the result of this fn call,
835 // drop the temporary slot we made.
836 match (dest, opt_llretslot, ret_ty) {
837 (Some(expr::Ignore), Some(llretslot), ty::FnConverging(ret_ty)) => {
838 // drop the value if it is not being saved.
839 bcx = glue::drop_ty(bcx,
843 call_lifetime_end(bcx, llretslot);
848 if ret_ty == ty::FnDiverging {
852 Result::new(bcx, llresult)
855 pub enum CallArgs<'a, 'tcx> {
856 // Supply value of arguments as a list of expressions that must be
857 // translated. This is used in the common case of `foo(bar, qux)`.
858 ArgExprs(&'a [P<hir::Expr>]),
860 // Supply value of arguments as a list of LLVM value refs; frequently
861 // used with lang items and so forth, when the argument is an internal
863 ArgVals(&'a [ValueRef]),
865 // For overloaded operators: `(lhs, Option(rhs, rhs_id), autoref)`. `lhs`
866 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
867 // the right-hand-side argument (if any). `autoref` indicates whether the `rhs`
868 // arguments should be auto-referenced
869 ArgOverloadedOp(Datum<'tcx, Expr>, Option<(Datum<'tcx, Expr>, ast::NodeId)>, bool),
871 // Supply value of arguments as a list of expressions that must be
872 // translated, for overloaded call operators.
873 ArgOverloadedCall(Vec<&'a hir::Expr>),
876 fn trans_args_under_call_abi<'blk, 'tcx>(
877 mut bcx: Block<'blk, 'tcx>,
878 arg_exprs: &[P<hir::Expr>],
880 llargs: &mut Vec<ValueRef>,
881 arg_cleanup_scope: cleanup::ScopeId,
885 let args = bcx.tcx().erase_late_bound_regions(&fn_ty.fn_args());
887 // Translate the `self` argument first.
889 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
890 bcx = trans_arg_datum(bcx,
898 // Now untuple the rest of the arguments.
899 let tuple_expr = &arg_exprs[1];
900 let tuple_type = common::node_id_type(bcx, tuple_expr.id);
902 match tuple_type.sty {
903 ty::TyTuple(ref field_types) => {
904 let tuple_datum = unpack_datum!(bcx,
905 expr::trans(bcx, &**tuple_expr));
906 let tuple_lvalue_datum =
908 tuple_datum.to_lvalue_datum(bcx,
911 let repr = adt::represent_type(bcx.ccx(), tuple_type);
912 let repr_ptr = &*repr;
913 for (i, field_type) in field_types.iter().enumerate() {
914 let arg_datum = tuple_lvalue_datum.get_element(
918 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
920 bcx = trans_arg_datum(bcx,
929 bcx.sess().span_bug(tuple_expr.span,
930 "argument to `.call()` wasn't a tuple?!")
937 fn trans_overloaded_call_args<'blk, 'tcx>(
938 mut bcx: Block<'blk, 'tcx>,
939 arg_exprs: Vec<&hir::Expr>,
941 llargs: &mut Vec<ValueRef>,
942 arg_cleanup_scope: cleanup::ScopeId,
944 -> Block<'blk, 'tcx> {
945 // Translate the `self` argument first.
946 let arg_tys = bcx.tcx().erase_late_bound_regions( &fn_ty.fn_args());
948 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
949 bcx = trans_arg_datum(bcx,
957 // Now untuple the rest of the arguments.
958 let tuple_type = arg_tys[1];
959 match tuple_type.sty {
960 ty::TyTuple(ref field_types) => {
961 for (i, &field_type) in field_types.iter().enumerate() {
963 unpack_datum!(bcx, expr::trans(bcx, arg_exprs[i + 1]));
964 bcx = trans_arg_datum(bcx,
973 bcx.sess().span_bug(arg_exprs[0].span,
974 "argument to `.call()` wasn't a tuple?!")
981 pub fn trans_args<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
982 args: CallArgs<'a, 'tcx>,
984 llargs: &mut Vec<ValueRef>,
985 arg_cleanup_scope: cleanup::ScopeId,
988 -> Block<'blk, 'tcx> {
989 debug!("trans_args(abi={})", abi);
991 let _icx = push_ctxt("trans_args");
992 let arg_tys = cx.tcx().erase_late_bound_regions(&fn_ty.fn_args());
993 let variadic = fn_ty.fn_sig().0.variadic;
997 // First we figure out the caller's view of the types of the arguments.
998 // This will be needed if this is a generic call, because the callee has
999 // to cast her view of the arguments to the caller's view.
1001 ArgExprs(arg_exprs) => {
1002 if abi == synabi::RustCall {
1003 // This is only used for direct calls to the `call`,
1004 // `call_mut` or `call_once` functions.
1005 return trans_args_under_call_abi(cx,
1013 let num_formal_args = arg_tys.len();
1014 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1015 if i == 0 && ignore_self {
1018 let arg_ty = if i >= num_formal_args {
1020 common::expr_ty_adjusted(cx, &**arg_expr)
1025 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1026 bcx = trans_arg_datum(bcx, arg_ty, arg_datum,
1032 ArgOverloadedCall(arg_exprs) => {
1033 return trans_overloaded_call_args(cx,
1040 ArgOverloadedOp(lhs, rhs, autoref) => {
1043 bcx = trans_arg_datum(bcx, arg_tys[0], lhs,
1048 if let Some((rhs, rhs_id)) = rhs {
1049 assert_eq!(arg_tys.len(), 2);
1050 bcx = trans_arg_datum(bcx, arg_tys[1], rhs,
1052 if autoref { DoAutorefArg(rhs_id) } else { DontAutorefArg },
1055 assert_eq!(arg_tys.len(), 1);
1059 llargs.push_all(vs);
1066 #[derive(Copy, Clone)]
1067 pub enum AutorefArg {
1069 DoAutorefArg(ast::NodeId)
1072 pub fn trans_arg_datum<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1073 formal_arg_ty: Ty<'tcx>,
1074 arg_datum: Datum<'tcx, Expr>,
1075 arg_cleanup_scope: cleanup::ScopeId,
1076 autoref_arg: AutorefArg,
1077 llargs: &mut Vec<ValueRef>)
1078 -> Block<'blk, 'tcx> {
1079 let _icx = push_ctxt("trans_arg_datum");
1081 let ccx = bcx.ccx();
1083 debug!("trans_arg_datum({:?})",
1086 let arg_datum_ty = arg_datum.ty;
1088 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1091 // FIXME(#3548) use the adjustments table
1093 DoAutorefArg(arg_id) => {
1094 // We will pass argument by reference
1095 // We want an lvalue, so that we can pass by reference and
1096 let arg_datum = unpack_datum!(
1097 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1098 val = arg_datum.val;
1100 DontAutorefArg if common::type_is_fat_ptr(bcx.tcx(), arg_datum_ty) &&
1101 !bcx.fcx.type_needs_drop(arg_datum_ty) => {
1105 // Make this an rvalue, since we are going to be
1106 // passing ownership.
1107 let arg_datum = unpack_datum!(
1108 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1110 // Now that arg_datum is owned, get it into the appropriate
1111 // mode (ref vs value).
1112 let arg_datum = unpack_datum!(
1113 bcx, arg_datum.to_appropriate_datum(bcx));
1115 // Technically, ownership of val passes to the callee.
1116 // However, we must cleanup should we panic before the
1117 // callee is actually invoked.
1118 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1122 if type_of::arg_is_indirect(ccx, formal_arg_ty) && formal_arg_ty != arg_datum_ty {
1123 // this could happen due to e.g. subtyping
1124 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1125 debug!("casting actual type ({}) to match formal ({})",
1126 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1127 debug!("Rust types: {:?}; {:?}", arg_datum_ty,
1129 val = PointerCast(bcx, val, llformal_arg_ty);
1132 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1134 if common::type_is_fat_ptr(bcx.tcx(), formal_arg_ty) {
1135 llargs.push(Load(bcx, expr::get_dataptr(bcx, val)));
1136 llargs.push(Load(bcx, expr::get_meta(bcx, val)));