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;
27 use metadata::csearch;
30 use middle::subst::{Subst, Substs};
37 use trans::cleanup::CleanupMethods;
48 use trans::monomorphize;
49 use trans::type_::Type;
51 use middle::ty::{mod, Ty};
52 use middle::ty::MethodCall;
53 use util::ppaux::Repr;
54 use util::ppaux::ty_to_string;
56 use syntax::abi as synabi;
62 pub struct MethodData {
67 pub enum CalleeData<'tcx> {
68 Closure(Datum<'tcx, Lvalue>),
70 // Constructor for enum variant/tuple-like-struct
72 NamedTupleConstructor(subst::Substs<'tcx>, ty::Disr),
74 // Represents a (possibly monomorphized) top-level fn item or method
75 // item. Note that this is just the fn-ptr and is not a Rust closure
76 // value (which is a pair).
77 Fn(/* llfn */ ValueRef),
79 Intrinsic(ast::NodeId, subst::Substs<'tcx>),
84 pub struct Callee<'blk, 'tcx: 'blk> {
85 pub bcx: Block<'blk, 'tcx>,
86 pub data: CalleeData<'tcx>,
89 fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
90 -> Callee<'blk, 'tcx> {
91 let _icx = push_ctxt("trans_callee");
92 debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
94 // pick out special kinds of expressions that can be called:
95 if let ast::ExprPath(_) = expr.node {
96 return trans_def(bcx, bcx.def(expr.id), expr);
99 // any other expressions are closures:
100 return datum_callee(bcx, expr);
102 fn datum_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
103 -> Callee<'blk, 'tcx> {
104 let DatumBlock {mut bcx, datum} = expr::trans(bcx, expr);
106 ty::ty_bare_fn(..) => {
107 let llval = datum.to_llscalarish(bcx);
113 ty::ty_closure(..) => {
114 let datum = unpack_datum!(
115 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
118 data: Closure(datum),
122 bcx.tcx().sess.span_bug(
124 format!("type of callee is neither bare-fn nor closure: \
126 bcx.ty_to_string(datum.ty))[]);
131 fn fn_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, llfn: ValueRef)
132 -> Callee<'blk, 'tcx> {
139 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
141 ref_expr: &ast::Expr)
142 -> Callee<'blk, 'tcx> {
143 debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
144 let expr_ty = node_id_type(bcx, ref_expr.id);
146 def::DefFn(did, _) if {
147 let maybe_def_id = inline::get_local_instance(bcx.ccx(), did);
148 let maybe_ast_node = maybe_def_id.and_then(|def_id| bcx.tcx().map
150 match maybe_ast_node {
151 Some(ast_map::NodeStructCtor(_)) => true,
155 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
158 data: NamedTupleConstructor(substs, 0)
161 def::DefFn(did, _) if match expr_ty.sty {
162 ty::ty_bare_fn(_, ref f) => f.abi == synabi::RustIntrinsic,
165 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
166 let def_id = inline::maybe_instantiate_inline(bcx.ccx(), did);
167 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
169 def::DefFn(did, _) | def::DefMethod(did, _, def::FromImpl(_)) |
170 def::DefStaticMethod(did, def::FromImpl(_)) => {
171 fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
173 def::DefStaticMethod(meth_did, def::FromTrait(trait_did)) |
174 def::DefMethod(meth_did, _, def::FromTrait(trait_did)) => {
175 fn_callee(bcx, meth::trans_static_method_callee(bcx, meth_did,
179 def::DefVariant(tid, vid, _) => {
180 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
181 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
183 // Nullary variants are not callable
184 assert!(vinfo.args.len() > 0u);
188 data: NamedTupleConstructor(substs, vinfo.disr_val)
191 def::DefStruct(_) => {
192 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
195 data: NamedTupleConstructor(substs, 0)
201 def::DefUpvar(..) => {
202 datum_callee(bcx, ref_expr)
204 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
205 def::DefTy(..) | def::DefPrimTy(..) | def::DefAssociatedTy(..) |
206 def::DefUse(..) | def::DefTyParamBinder(..) |
207 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
208 def::DefSelfTy(..) | def::DefAssociatedPath(..) => {
209 bcx.tcx().sess.span_bug(
211 format!("cannot translate def {} \
212 to a callable thing!", def)[]);
218 /// Translates a reference (with id `ref_id`) to the fn/method with id `def_id` into a function
219 /// pointer. This may require monomorphization or inlining.
220 pub fn trans_fn_ref(bcx: Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
221 let _icx = push_ctxt("trans_fn_ref");
223 let substs = node_id_substs(bcx, node);
224 debug!("trans_fn_ref(def_id={}, node={}, substs={})",
225 def_id.repr(bcx.tcx()),
227 substs.repr(bcx.tcx()));
228 trans_fn_ref_with_substs(bcx, def_id, node, substs)
231 fn trans_fn_ref_with_substs_to_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
234 substs: subst::Substs<'tcx>)
235 -> Callee<'blk, 'tcx> {
238 data: Fn(trans_fn_ref_with_substs(bcx,
245 /// Translates an adapter that implements the `Fn` trait for a fn
246 /// pointer. This is basically the equivalent of something like:
249 /// impl<'a> Fn(&'a int) -> &'a int for fn(&int) -> &int {
250 /// extern "rust-abi" fn call(&self, args: (&'a int,)) -> &'a int {
256 /// but for the bare function type given.
257 pub fn trans_fn_pointer_shim<'a, 'tcx>(
258 ccx: &'a CrateContext<'a, 'tcx>,
259 bare_fn_ty: Ty<'tcx>)
262 let _icx = push_ctxt("trans_fn_pointer_shim");
265 let bare_fn_ty = ty::normalize_ty(tcx, bare_fn_ty);
266 match ccx.fn_pointer_shims().borrow().get(&bare_fn_ty) {
267 Some(&llval) => { return llval; }
271 debug!("trans_fn_pointer_shim(bare_fn_ty={})",
272 bare_fn_ty.repr(tcx));
274 // This is an impl of `Fn` trait, so receiver is `&self`.
275 let bare_fn_ty_ref = ty::mk_imm_rptr(tcx, tcx.mk_region(ty::ReStatic), bare_fn_ty);
277 // Construct the "tuply" version of `bare_fn_ty`. It takes two arguments: `self`,
278 // which is the fn pointer, and `args`, which is the arguments tuple.
279 let (opt_def_id, input_tys, output_ty) =
280 match bare_fn_ty.sty {
281 ty::ty_bare_fn(opt_def_id,
282 &ty::BareFnTy { unsafety: ast::Unsafety::Normal,
284 sig: ty::Binder(ty::FnSig { inputs: ref input_tys,
286 variadic: false })}) =>
288 (opt_def_id, input_tys, output_ty)
292 tcx.sess.bug(format!("trans_fn_pointer_shim invoked on invalid type: {}",
293 bare_fn_ty.repr(tcx))[]);
296 let tuple_input_ty = ty::mk_tup(tcx, input_tys.to_vec());
297 let tuple_fn_ty = ty::mk_bare_fn(tcx,
299 tcx.mk_bare_fn(ty::BareFnTy {
300 unsafety: ast::Unsafety::Normal,
301 abi: synabi::RustCall,
302 sig: ty::Binder(ty::FnSig {
303 inputs: vec![bare_fn_ty_ref,
308 debug!("tuple_fn_ty: {}", tuple_fn_ty.repr(tcx));
312 link::mangle_internal_name_by_type_and_seq(ccx, bare_fn_ty,
315 decl_internal_rust_fn(ccx,
320 let block_arena = TypedArena::new();
321 let empty_substs = Substs::trans_empty();
322 let fcx = new_fn_ctxt(ccx,
330 let mut bcx = init_function(&fcx, false, output_ty);
332 // the first argument (`self`) will be ptr to the the fn pointer
334 Load(bcx, get_param(fcx.llfn, fcx.arg_pos(0) as u32));
336 // the remaining arguments will be the untupled values
340 .map(|(i, _)| get_param(fcx.llfn, fcx.arg_pos(i+1) as u32))
342 assert!(!fcx.needs_ret_allocas);
344 let dest = fcx.llretslotptr.get().map(|_|
345 expr::SaveIn(fcx.get_ret_slot(bcx, output_ty, "ret_slot"))
348 bcx = trans_call_inner(bcx,
351 |bcx, _| Callee { bcx: bcx, data: Fn(llfnpointer) },
355 finish_fn(&fcx, bcx, output_ty);
357 ccx.fn_pointer_shims().borrow_mut().insert(bare_fn_ty, llfn);
362 /// Translates a reference to a fn/method item, monomorphizing and
363 /// inlining as it goes.
367 /// - `bcx`: the current block where the reference to the fn occurs
368 /// - `def_id`: def id of the fn or method item being referenced
369 /// - `node`: node id of the reference to the fn/method, if applicable.
370 /// This parameter may be zero; but, if so, the resulting value may not
371 /// have the right type, so it must be cast before being used.
372 /// - `substs`: values for each of the fn/method's parameters
373 pub fn trans_fn_ref_with_substs<'blk, 'tcx>(
374 bcx: Block<'blk, 'tcx>, //
375 def_id: ast::DefId, // def id of fn
376 node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
377 substs: subst::Substs<'tcx>) // vtables for the call
380 let _icx = push_ctxt("trans_fn_ref_with_substs");
384 debug!("trans_fn_ref_with_substs(bcx={}, def_id={}, node={}, \
391 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
392 assert!(substs.types.all(|t| !ty::type_has_escaping_regions(*t)));
393 let substs = substs.erase_regions();
395 // Load the info for the appropriate trait if necessary.
396 match ty::trait_of_item(tcx, def_id) {
399 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
403 // We need to do a bunch of special handling for default methods.
404 // We need to modify the def_id and our substs in order to monomorphize
406 let (is_default, def_id, substs) = match ty::provided_source(tcx, def_id) {
407 None => (false, def_id, substs),
409 // There are two relevant substitutions when compiling
410 // default methods. First, there is the substitution for
411 // the type parameters of the impl we are using and the
412 // method we are calling. This substitution is the substs
413 // argument we already have.
414 // In order to compile a default method, though, we need
415 // to consider another substitution: the substitution for
416 // the type parameters on trait; the impl we are using
417 // implements the trait at some particular type
418 // parameters, and we need to substitute for those first.
419 // So, what we need to do is find this substitution and
420 // compose it with the one we already have.
422 let impl_id = ty::impl_or_trait_item(tcx, def_id).container()
424 let impl_or_trait_item = ty::impl_or_trait_item(tcx, source_id);
425 match impl_or_trait_item {
426 ty::MethodTraitItem(method) => {
427 let trait_ref = ty::impl_trait_ref(tcx, impl_id).unwrap();
429 // Compute the first substitution
431 ty::make_substs_for_receiver_types(tcx, &*trait_ref, &*method)
435 let new_substs = first_subst.subst(tcx, &substs);
437 debug!("trans_fn_with_vtables - default method: \
438 substs = {}, trait_subst = {}, \
439 first_subst = {}, new_subst = {}",
440 substs.repr(tcx), trait_ref.substs.repr(tcx),
441 first_subst.repr(tcx), new_substs.repr(tcx));
443 (true, source_id, new_substs)
445 ty::TypeTraitItem(_) => {
446 bcx.tcx().sess.bug("trans_fn_ref_with_vtables() tried \
447 to translate an associated type?!")
453 // If this is an unboxed closure, redirect to it.
454 match closure::get_or_create_declaration_if_unboxed_closure(bcx,
458 Some(llfn) => return llfn,
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.krate == ast::LOCAL_CRATE {
470 let map_node = session::expect(
472 tcx.map.find(def_id.node),
473 || "local item should be in ast map".to_string());
476 ast_map::NodeVariant(v) => match v.node.kind {
477 ast::TupleVariantKind(ref args) => args.len() > 0,
480 ast_map::NodeStructCtor(_) => true,
487 // Create a monomorphic version of generic functions
488 if must_monomorphise {
489 // Should be either intra-crate or inlined.
490 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
492 let opt_ref_id = match node {
493 ExprId(id) => if id != 0 { Some(id) } else { None },
494 MethodCallKey(_) => None,
497 let (val, must_cast) =
498 monomorphize::monomorphic_fn(ccx, def_id, &substs, opt_ref_id);
500 if must_cast && node != ExprId(0) {
501 // Monotype of the REFERENCE to the function (type params
503 let ref_ty = match node {
504 ExprId(id) => node_id_type(bcx, id),
505 MethodCallKey(method_call) => {
506 let t = (*bcx.tcx().method_map.borrow())[method_call].ty;
507 monomorphize_type(bcx, t)
512 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
517 // Type scheme of the function item (may have type params)
518 let fn_type_scheme = ty::lookup_item_type(tcx, def_id);
519 let fn_type = monomorphize::normalize_associated_type(tcx, &fn_type_scheme.ty);
521 // Find the actual function pointer.
523 if def_id.krate == ast::LOCAL_CRATE {
524 // Internal reference.
525 get_item_val(ccx, def_id.node)
527 // External reference.
528 trans_external_path(ccx, def_id, fn_type)
532 // This is subtle and surprising, but sometimes we have to bitcast
533 // the resulting fn pointer. The reason has to do with external
534 // functions. If you have two crates that both bind the same C
535 // library, they may not use precisely the same types: for
536 // example, they will probably each declare their own structs,
537 // which are distinct types from LLVM's point of view (nominal
540 // Now, if those two crates are linked into an application, and
541 // they contain inlined code, you can wind up with a situation
542 // where both of those functions wind up being loaded into this
543 // application simultaneously. In that case, the same function
544 // (from LLVM's point of view) requires two types. But of course
545 // LLVM won't allow one function to have two types.
547 // What we currently do, therefore, is declare the function with
548 // one of the two types (whichever happens to come first) and then
549 // bitcast as needed when the function is referenced to make sure
550 // it has the type we expect.
552 // This can occur on either a crate-local or crate-external
553 // reference. It also occurs when testing libcore and in some
554 // other weird situations. Annoying.
555 let llty = type_of::type_of_fn_from_ty(ccx, fn_type);
556 let llptrty = llty.ptr_to();
557 if val_ty(val) != llptrty {
558 debug!("trans_fn_ref_with_vtables(): casting pointer!");
559 val = BitCast(bcx, val, llptrty);
561 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
567 // ______________________________________________________________________
570 pub fn trans_call<'a, 'blk, 'tcx>(in_cx: Block<'blk, 'tcx>,
573 args: CallArgs<'a, 'tcx>,
575 -> Block<'blk, 'tcx> {
576 let _icx = push_ctxt("trans_call");
577 trans_call_inner(in_cx,
578 Some(common::expr_info(call_ex)),
580 |cx, _| trans(cx, f),
585 pub fn trans_method_call<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
588 args: CallArgs<'a, 'tcx>,
590 -> Block<'blk, 'tcx> {
591 let _icx = push_ctxt("trans_method_call");
592 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
593 let method_call = MethodCall::expr(call_ex.id);
594 let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
597 Some(common::expr_info(call_ex)),
598 monomorphize_type(bcx, method_ty),
599 |cx, arg_cleanup_scope| {
600 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
606 pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
609 dest: Option<expr::Dest>)
610 -> Result<'blk, 'tcx> {
611 let fty = if did.krate == ast::LOCAL_CRATE {
612 ty::node_id_to_type(bcx.tcx(), did.node)
614 csearch::get_type(bcx.tcx(), did).ty
616 callee::trans_call_inner(bcx,
620 trans_fn_ref_with_substs_to_callee(bcx,
623 subst::Substs::trans_empty())
629 /// This behemoth of a function translates function calls. Unfortunately, in order to generate more
630 /// efficient LLVM output at -O0, it has quite a complex signature (refactoring this into two
631 /// functions seems like a good idea).
633 /// In particular, for lang items, it is invoked with a dest of None, and in that case the return
634 /// value contains the result of the fn. The lang item must not return a structural type or else
635 /// all heck breaks loose.
637 /// For non-lang items, `dest` is always Some, and hence the result is written into memory
638 /// somewhere. Nonetheless we return the actual return value of the function.
639 pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
640 call_info: Option<NodeInfo>,
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::ty_bare_fn(_, ref f) => (f.abi, f.sig.0.output),
664 ty::ty_closure(ref f) => (f.abi, f.sig.0.output),
665 _ => panic!("expected bare rust fn or closure in trans_call_inner")
668 let (llfn, llenv, llself) = match callee.data {
673 (d.llfn, None, Some(d.llself))
676 // Closures are represented as (llfn, llclosure) pair:
677 // load the requisite values out.
678 let pair = d.to_llref();
679 let llfn = GEPi(bcx, pair, &[0u, abi::FAT_PTR_ADDR]);
680 let llfn = Load(bcx, llfn);
681 let llenv = GEPi(bcx, pair, &[0u, abi::FAT_PTR_EXTRA]);
682 let llenv = Load(bcx, llenv);
683 (llfn, Some(llenv), None)
685 Intrinsic(node, substs) => {
686 assert!(abi == synabi::RustIntrinsic);
687 assert!(dest.is_some());
689 let call_info = call_info.expect("no call info for intrinsic call?");
690 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
691 arg_cleanup_scope, args,
692 dest.unwrap(), substs,
695 NamedTupleConstructor(substs, disr) => {
696 assert!(dest.is_some());
697 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
699 let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
700 return base::trans_named_tuple_constructor(bcx,
709 // Intrinsics should not become actual functions.
710 // We trans them in place in `trans_intrinsic_call`
711 assert!(abi != synabi::RustIntrinsic);
713 let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
715 // Generate a location to store the result. If the user does
716 // not care about the result, just make a stack slot.
717 let opt_llretslot = dest.and_then(|dest| match dest {
718 expr::SaveIn(dst) => Some(dst),
720 let ret_ty = match ret_ty {
721 ty::FnConverging(ret_ty) => ret_ty,
722 ty::FnDiverging => ty::mk_nil(ccx.tcx())
725 type_of::return_uses_outptr(ccx, ret_ty) ||
726 type_needs_drop(bcx.tcx(), ret_ty) {
727 // Push the out-pointer if we use an out-pointer for this
728 // return type, otherwise push "undef".
729 if type_is_zero_size(ccx, ret_ty) {
730 let llty = type_of::type_of(ccx, ret_ty);
731 Some(C_undef(llty.ptr_to()))
733 Some(alloc_ty(bcx, ret_ty, "__llret"))
741 let mut llresult = unsafe {
742 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
745 // The code below invokes the function, using either the Rust
746 // conventions (if it is a rust fn) or the native conventions
747 // (otherwise). The important part is that, when all is said
748 // and done, either the return value of the function will have been
749 // written in opt_llretslot (if it is Some) or `llresult` will be
750 // set appropriately (otherwise).
752 let mut llargs = Vec::new();
754 if let (ty::FnConverging(ret_ty), Some(llretslot)) = (ret_ty, opt_llretslot) {
755 if type_of::return_uses_outptr(ccx, ret_ty) {
756 llargs.push(llretslot);
760 // Push the environment (or a trait object's self).
761 match (llenv, llself) {
762 (Some(llenv), None) => llargs.push(llenv),
763 (None, Some(llself)) => llargs.push(llself),
767 // Push the arguments.
768 bcx = trans_args(bcx,
772 cleanup::CustomScope(arg_cleanup_scope),
776 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
778 // Invoke the actual rust fn and update bcx/llresult.
779 let (llret, b) = base::invoke(bcx,
787 // If the Rust convention for this type is return via
788 // the return value, copy it into llretslot.
789 match (opt_llretslot, ret_ty) {
790 (Some(llretslot), ty::FnConverging(ret_ty)) => {
791 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
792 !type_is_zero_size(bcx.ccx(), ret_ty)
794 store_ty(bcx, llret, llretslot, ret_ty)
800 // Lang items are the only case where dest is None, and
801 // they are always Rust fns.
802 assert!(dest.is_some());
804 let mut llargs = Vec::new();
805 let arg_tys = match args {
806 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
807 _ => panic!("expected arg exprs.")
809 bcx = trans_args(bcx,
813 cleanup::CustomScope(arg_cleanup_scope),
816 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
818 bcx = foreign::trans_native_call(bcx, callee_ty,
819 llfn, opt_llretslot.unwrap(),
823 fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_cleanup_scope);
825 // If the caller doesn't care about the result of this fn call,
826 // drop the temporary slot we made.
827 match (dest, opt_llretslot, ret_ty) {
828 (Some(expr::Ignore), Some(llretslot), ty::FnConverging(ret_ty)) => {
829 // drop the value if it is not being saved.
830 bcx = glue::drop_ty(bcx, llretslot, ret_ty, call_info);
831 call_lifetime_end(bcx, llretslot);
836 if ret_ty == ty::FnDiverging {
840 Result::new(bcx, llresult)
843 pub enum CallArgs<'a, 'tcx> {
844 // Supply value of arguments as a list of expressions that must be
845 // translated. This is used in the common case of `foo(bar, qux)`.
846 ArgExprs(&'a [P<ast::Expr>]),
848 // Supply value of arguments as a list of LLVM value refs; frequently
849 // used with lang items and so forth, when the argument is an internal
851 ArgVals(&'a [ValueRef]),
853 // For overloaded operators: `(lhs, Vec(rhs, rhs_id), autoref)`. `lhs`
854 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
855 // the right-hand-side arguments (if any). `autoref` indicates whether the `rhs`
856 // arguments should be auto-referenced
857 ArgOverloadedOp(Datum<'tcx, Expr>, Vec<(Datum<'tcx, Expr>, ast::NodeId)>, bool),
859 // Supply value of arguments as a list of expressions that must be
860 // translated, for overloaded call operators.
861 ArgOverloadedCall(Vec<&'a ast::Expr>),
864 fn trans_args_under_call_abi<'blk, 'tcx>(
865 mut bcx: Block<'blk, 'tcx>,
866 arg_exprs: &[P<ast::Expr>],
868 llargs: &mut Vec<ValueRef>,
869 arg_cleanup_scope: cleanup::ScopeId,
871 -> Block<'blk, 'tcx> {
872 // Translate the `self` argument first.
874 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
875 llargs.push(unpack_result!(bcx, {
877 ty::ty_fn_args(fn_ty)[0],
884 // Now untuple the rest of the arguments.
885 let tuple_expr = &arg_exprs[1];
886 let tuple_type = node_id_type(bcx, tuple_expr.id);
888 match tuple_type.sty {
889 ty::ty_tup(ref field_types) => {
890 let tuple_datum = unpack_datum!(bcx,
891 expr::trans(bcx, &**tuple_expr));
892 let tuple_lvalue_datum =
894 tuple_datum.to_lvalue_datum(bcx,
897 let repr = adt::represent_type(bcx.ccx(), tuple_type);
898 let repr_ptr = &*repr;
899 for i in range(0, field_types.len()) {
900 let arg_datum = tuple_lvalue_datum.get_element(
904 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
906 let arg_datum = arg_datum.to_expr_datum();
908 unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
910 unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
911 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
915 bcx.sess().span_bug(tuple_expr.span,
916 "argument to `.call()` wasn't a tuple?!")
923 fn trans_overloaded_call_args<'blk, 'tcx>(
924 mut bcx: Block<'blk, 'tcx>,
925 arg_exprs: Vec<&ast::Expr>,
927 llargs: &mut Vec<ValueRef>,
928 arg_cleanup_scope: cleanup::ScopeId,
930 -> Block<'blk, 'tcx> {
931 // Translate the `self` argument first.
932 let arg_tys = ty::ty_fn_args(fn_ty);
934 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
935 llargs.push(unpack_result!(bcx, {
944 // Now untuple the rest of the arguments.
945 let tuple_type = arg_tys[1];
946 match tuple_type.sty {
947 ty::ty_tup(ref field_types) => {
948 for (i, &field_type) in field_types.iter().enumerate() {
950 unpack_datum!(bcx, expr::trans(bcx, arg_exprs[i + 1]));
951 llargs.push(unpack_result!(bcx, {
961 bcx.sess().span_bug(arg_exprs[0].span,
962 "argument to `.call()` wasn't a tuple?!")
969 pub fn trans_args<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
970 args: CallArgs<'a, 'tcx>,
972 llargs: &mut Vec<ValueRef>,
973 arg_cleanup_scope: cleanup::ScopeId,
976 -> Block<'blk, 'tcx> {
977 debug!("trans_args(abi={})", abi);
979 let _icx = push_ctxt("trans_args");
980 let arg_tys = ty::ty_fn_args(fn_ty);
981 let variadic = ty::fn_is_variadic(fn_ty);
985 // First we figure out the caller's view of the types of the arguments.
986 // This will be needed if this is a generic call, because the callee has
987 // to cast her view of the arguments to the caller's view.
989 ArgExprs(arg_exprs) => {
990 if abi == synabi::RustCall {
991 // This is only used for direct calls to the `call`,
992 // `call_mut` or `call_once` functions.
993 return trans_args_under_call_abi(cx,
1001 let num_formal_args = arg_tys.len();
1002 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1003 if i == 0 && ignore_self {
1006 let arg_ty = if i >= num_formal_args {
1008 expr_ty_adjusted(cx, &**arg_expr)
1013 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1014 llargs.push(unpack_result!(bcx, {
1015 trans_arg_datum(bcx, arg_ty, arg_datum,
1021 ArgOverloadedCall(arg_exprs) => {
1022 return trans_overloaded_call_args(cx,
1029 ArgOverloadedOp(lhs, rhs, autoref) => {
1032 llargs.push(unpack_result!(bcx, {
1033 trans_arg_datum(bcx, arg_tys[0], lhs,
1038 assert_eq!(arg_tys.len(), 1 + rhs.len());
1039 for (rhs, rhs_id) in rhs.into_iter() {
1040 llargs.push(unpack_result!(bcx, {
1041 trans_arg_datum(bcx, arg_tys[1], rhs,
1043 if autoref { DoAutorefArg(rhs_id) } else { DontAutorefArg })
1048 llargs.push_all(vs);
1056 pub enum AutorefArg {
1058 DoAutorefArg(ast::NodeId)
1061 pub fn trans_arg_datum<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1062 formal_arg_ty: Ty<'tcx>,
1063 arg_datum: Datum<'tcx, Expr>,
1064 arg_cleanup_scope: cleanup::ScopeId,
1065 autoref_arg: AutorefArg)
1066 -> Result<'blk, 'tcx> {
1067 let _icx = push_ctxt("trans_arg_datum");
1069 let ccx = bcx.ccx();
1071 debug!("trans_arg_datum({})",
1072 formal_arg_ty.repr(bcx.tcx()));
1074 let arg_datum_ty = arg_datum.ty;
1076 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1079 // FIXME(#3548) use the adjustments table
1081 DoAutorefArg(arg_id) => {
1082 // We will pass argument by reference
1083 // We want an lvalue, so that we can pass by reference and
1084 let arg_datum = unpack_datum!(
1085 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1086 val = arg_datum.val;
1089 // Make this an rvalue, since we are going to be
1090 // passing ownership.
1091 let arg_datum = unpack_datum!(
1092 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1094 // Now that arg_datum is owned, get it into the appropriate
1095 // mode (ref vs value).
1096 let arg_datum = unpack_datum!(
1097 bcx, arg_datum.to_appropriate_datum(bcx));
1099 // Technically, ownership of val passes to the callee.
1100 // However, we must cleanup should we panic before the
1101 // callee is actually invoked.
1102 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1106 if formal_arg_ty != arg_datum_ty {
1107 // this could happen due to e.g. subtyping
1108 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1109 debug!("casting actual type ({}) to match formal ({})",
1110 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1111 debug!("Rust types: {}; {}", ty_to_string(bcx.tcx(), arg_datum_ty),
1112 ty_to_string(bcx.tcx(), formal_arg_ty));
1113 val = PointerCast(bcx, val, llformal_arg_ty);
1116 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1117 Result::new(bcx, val)