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;
49 use trans::monomorphize;
50 use trans::type_::Type;
52 use middle::ty::{self, Ty};
53 use middle::ty::MethodCall;
54 use util::ppaux::Repr;
55 use util::ppaux::ty_to_string;
57 use syntax::abi as synabi;
63 pub struct MethodData {
68 pub enum CalleeData<'tcx> {
69 Closure(Datum<'tcx, Lvalue>),
71 // Constructor for enum variant/tuple-like-struct
73 NamedTupleConstructor(subst::Substs<'tcx>, ty::Disr),
75 // Represents a (possibly monomorphized) top-level fn item or method
76 // item. Note that this is just the fn-ptr and is not a Rust closure
77 // value (which is a pair).
78 Fn(/* llfn */ ValueRef),
80 Intrinsic(ast::NodeId, subst::Substs<'tcx>),
85 pub struct Callee<'blk, 'tcx: 'blk> {
86 pub bcx: Block<'blk, 'tcx>,
87 pub data: CalleeData<'tcx>,
90 fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
91 -> Callee<'blk, 'tcx> {
92 let _icx = push_ctxt("trans_callee");
93 debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
95 // pick out special kinds of expressions that can be called:
96 if let ast::ExprPath(_) = expr.node {
97 return trans_def(bcx, bcx.def(expr.id), expr);
100 // any other expressions are closures:
101 return datum_callee(bcx, expr);
103 fn datum_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
104 -> Callee<'blk, 'tcx> {
105 let DatumBlock {mut bcx, datum} = expr::trans(bcx, expr);
107 ty::ty_bare_fn(..) => {
108 let llval = datum.to_llscalarish(bcx);
114 ty::ty_closure(..) => {
115 let datum = unpack_datum!(
116 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
119 data: Closure(datum),
123 bcx.tcx().sess.span_bug(
125 format!("type of callee is neither bare-fn nor closure: \
127 bcx.ty_to_string(datum.ty))[]);
132 fn fn_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, llfn: ValueRef)
133 -> Callee<'blk, 'tcx> {
140 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
142 ref_expr: &ast::Expr)
143 -> Callee<'blk, 'tcx> {
144 debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
145 let expr_ty = node_id_type(bcx, ref_expr.id);
147 def::DefFn(did, _) if {
148 let maybe_def_id = inline::get_local_instance(bcx.ccx(), did);
149 let maybe_ast_node = maybe_def_id.and_then(|def_id| bcx.tcx().map
151 match maybe_ast_node {
152 Some(ast_map::NodeStructCtor(_)) => true,
156 let substs = node_id_substs(bcx.ccx(), ExprId(ref_expr.id),
157 bcx.fcx.param_substs);
160 data: NamedTupleConstructor(substs, 0)
163 def::DefFn(did, _) if match expr_ty.sty {
164 ty::ty_bare_fn(_, ref f) => f.abi == synabi::RustIntrinsic,
167 let substs = node_id_substs(bcx.ccx(), ExprId(ref_expr.id),
168 bcx.fcx.param_substs);
169 let def_id = inline::maybe_instantiate_inline(bcx.ccx(), did);
170 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
172 def::DefFn(did, _) | def::DefMethod(did, _, def::FromImpl(_)) |
173 def::DefStaticMethod(did, def::FromImpl(_)) => {
174 fn_callee(bcx, trans_fn_ref(bcx.ccx(), did, ExprId(ref_expr.id),
175 bcx.fcx.param_substs).val)
177 def::DefStaticMethod(meth_did, def::FromTrait(trait_did)) |
178 def::DefMethod(meth_did, _, def::FromTrait(trait_did)) => {
179 fn_callee(bcx, meth::trans_static_method_callee(bcx.ccx(),
183 bcx.fcx.param_substs).val)
185 def::DefVariant(tid, vid, _) => {
186 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
187 let substs = node_id_substs(bcx.ccx(), ExprId(ref_expr.id),
188 bcx.fcx.param_substs);
190 // Nullary variants are not callable
191 assert!(vinfo.args.len() > 0u);
195 data: NamedTupleConstructor(substs, vinfo.disr_val)
198 def::DefStruct(_) => {
199 let substs = node_id_substs(bcx.ccx(), ExprId(ref_expr.id),
200 bcx.fcx.param_substs);
203 data: NamedTupleConstructor(substs, 0)
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::DefTyParamBinder(..) |
215 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
216 def::DefSelfTy(..) | def::DefAssociatedPath(..) => {
217 bcx.tcx().sess.span_bug(
219 format!("cannot translate def {} \
220 to a callable thing!", def)[]);
226 /// Translates a reference (with id `ref_id`) to the fn/method with id `def_id` into a function
227 /// pointer. This may require monomorphization or inlining.
228 pub fn trans_fn_ref<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
230 node: ExprOrMethodCall,
231 param_substs: &subst::Substs<'tcx>)
232 -> Datum<'tcx, Rvalue> {
233 let _icx = push_ctxt("trans_fn_ref");
235 let substs = node_id_substs(ccx, node, param_substs);
236 debug!("trans_fn_ref(def_id={}, node={}, substs={})",
237 def_id.repr(ccx.tcx()),
239 substs.repr(ccx.tcx()));
240 trans_fn_ref_with_substs(ccx, def_id, node, param_substs, substs)
243 fn trans_fn_ref_with_substs_to_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
246 substs: subst::Substs<'tcx>)
247 -> Callee<'blk, 'tcx> {
250 data: Fn(trans_fn_ref_with_substs(bcx.ccx(),
253 bcx.fcx.param_substs,
258 /// Translates an adapter that implements the `Fn` trait for a fn
259 /// pointer. This is basically the equivalent of something like:
262 /// impl<'a> Fn(&'a int) -> &'a int for fn(&int) -> &int {
263 /// extern "rust-abi" fn call(&self, args: (&'a int,)) -> &'a int {
269 /// but for the bare function type given.
270 pub fn trans_fn_pointer_shim<'a, 'tcx>(
271 ccx: &'a CrateContext<'a, 'tcx>,
272 bare_fn_ty: Ty<'tcx>)
275 let _icx = push_ctxt("trans_fn_pointer_shim");
278 let bare_fn_ty = ty::normalize_ty(tcx, bare_fn_ty);
279 match ccx.fn_pointer_shims().borrow().get(&bare_fn_ty) {
280 Some(&llval) => { return llval; }
284 debug!("trans_fn_pointer_shim(bare_fn_ty={})",
285 bare_fn_ty.repr(tcx));
287 // This is an impl of `Fn` trait, so receiver is `&self`.
288 let bare_fn_ty_ref = ty::mk_imm_rptr(tcx, tcx.mk_region(ty::ReStatic), bare_fn_ty);
290 // Construct the "tuply" version of `bare_fn_ty`. It takes two arguments: `self`,
291 // which is the fn pointer, and `args`, which is the arguments tuple.
292 let (opt_def_id, input_tys, output_ty) =
293 match bare_fn_ty.sty {
294 ty::ty_bare_fn(opt_def_id,
295 &ty::BareFnTy { unsafety: ast::Unsafety::Normal,
297 sig: ty::Binder(ty::FnSig { inputs: ref input_tys,
299 variadic: false })}) =>
301 (opt_def_id, input_tys, output_ty)
305 tcx.sess.bug(format!("trans_fn_pointer_shim invoked on invalid type: {}",
306 bare_fn_ty.repr(tcx))[]);
309 let tuple_input_ty = ty::mk_tup(tcx, input_tys.to_vec());
310 let tuple_fn_ty = ty::mk_bare_fn(tcx,
312 tcx.mk_bare_fn(ty::BareFnTy {
313 unsafety: ast::Unsafety::Normal,
314 abi: synabi::RustCall,
315 sig: ty::Binder(ty::FnSig {
316 inputs: vec![bare_fn_ty_ref,
321 debug!("tuple_fn_ty: {}", tuple_fn_ty.repr(tcx));
325 link::mangle_internal_name_by_type_and_seq(ccx, bare_fn_ty,
328 decl_internal_rust_fn(ccx,
333 let block_arena = TypedArena::new();
334 let empty_substs = Substs::trans_empty();
335 let fcx = new_fn_ctxt(ccx,
343 let mut bcx = init_function(&fcx, false, output_ty);
345 // the first argument (`self`) will be ptr to the the fn pointer
347 Load(bcx, get_param(fcx.llfn, fcx.arg_pos(0) as u32));
349 // the remaining arguments will be the untupled values
353 .map(|(i, _)| get_param(fcx.llfn, fcx.arg_pos(i+1) as u32))
355 assert!(!fcx.needs_ret_allocas);
357 let dest = fcx.llretslotptr.get().map(|_|
358 expr::SaveIn(fcx.get_ret_slot(bcx, output_ty, "ret_slot"))
361 bcx = trans_call_inner(bcx,
364 |bcx, _| Callee { bcx: bcx, data: Fn(llfnpointer) },
368 finish_fn(&fcx, bcx, output_ty);
370 ccx.fn_pointer_shims().borrow_mut().insert(bare_fn_ty, llfn);
375 /// Translates a reference to a fn/method item, monomorphizing and
376 /// inlining as it goes.
380 /// - `ccx`: the crate context
381 /// - `def_id`: def id of the fn or method item being referenced
382 /// - `node`: node id of the reference to the fn/method, if applicable.
383 /// This parameter may be zero; but, if so, the resulting value may not
384 /// have the right type, so it must be cast before being used.
385 /// - `param_substs`: if the `node` is in a polymorphic function, these
386 /// are the substitutions required to monomorphize its type
387 /// - `substs`: values for each of the fn/method's parameters
388 pub fn trans_fn_ref_with_substs<'a, 'tcx>(
389 ccx: &CrateContext<'a, 'tcx>,
391 node: ExprOrMethodCall,
392 param_substs: &subst::Substs<'tcx>,
393 substs: subst::Substs<'tcx>)
394 -> Datum<'tcx, Rvalue>
396 let _icx = push_ctxt("trans_fn_ref_with_substs");
399 debug!("trans_fn_ref_with_substs(def_id={}, node={}, \
400 param_substs={}, substs={})",
403 param_substs.repr(tcx),
406 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
407 assert!(substs.types.all(|t| !ty::type_has_escaping_regions(*t)));
408 let substs = substs.erase_regions();
410 // Load the info for the appropriate trait if necessary.
411 match ty::trait_of_item(tcx, def_id) {
414 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
418 // We need to do a bunch of special handling for default methods.
419 // We need to modify the def_id and our substs in order to monomorphize
421 let (is_default, def_id, substs) = match ty::provided_source(tcx, def_id) {
422 None => (false, def_id, substs),
424 // There are two relevant substitutions when compiling
425 // default methods. First, there is the substitution for
426 // the type parameters of the impl we are using and the
427 // method we are calling. This substitution is the substs
428 // argument we already have.
429 // In order to compile a default method, though, we need
430 // to consider another substitution: the substitution for
431 // the type parameters on trait; the impl we are using
432 // implements the trait at some particular type
433 // parameters, and we need to substitute for those first.
434 // So, what we need to do is find this substitution and
435 // compose it with the one we already have.
437 let impl_id = ty::impl_or_trait_item(tcx, def_id).container()
439 let impl_or_trait_item = ty::impl_or_trait_item(tcx, source_id);
440 match impl_or_trait_item {
441 ty::MethodTraitItem(method) => {
442 let trait_ref = ty::impl_trait_ref(tcx, impl_id).unwrap();
444 // Compute the first substitution
446 ty::make_substs_for_receiver_types(tcx, &*trait_ref, &*method)
450 let new_substs = first_subst.subst(tcx, &substs);
452 debug!("trans_fn_with_vtables - default method: \
453 substs = {}, trait_subst = {}, \
454 first_subst = {}, new_subst = {}",
455 substs.repr(tcx), trait_ref.substs.repr(tcx),
456 first_subst.repr(tcx), new_substs.repr(tcx));
458 (true, source_id, new_substs)
460 ty::TypeTraitItem(_) => {
461 tcx.sess.bug("trans_fn_ref_with_vtables() tried \
462 to translate an associated type?!")
468 // If this is an unboxed closure, redirect to it.
469 match closure::get_or_create_declaration_if_unboxed_closure(ccx,
473 Some(llfn) => return llfn,
476 // Check whether this fn has an inlined copy and, if so, redirect
477 // def_id to the local id of the inlined copy.
478 let def_id = inline::maybe_instantiate_inline(ccx, def_id);
480 // We must monomorphise if the fn has type parameters, is a default method,
481 // or is a named tuple constructor.
482 let must_monomorphise = if !substs.types.is_empty() || is_default {
484 } else if def_id.krate == ast::LOCAL_CRATE {
485 let map_node = session::expect(
487 tcx.map.find(def_id.node),
488 || "local item should be in ast map".to_string());
491 ast_map::NodeVariant(v) => match v.node.kind {
492 ast::TupleVariantKind(ref args) => args.len() > 0,
495 ast_map::NodeStructCtor(_) => true,
502 // Create a monomorphic version of generic functions
503 if must_monomorphise {
504 // Should be either intra-crate or inlined.
505 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
507 let opt_ref_id = match node {
508 ExprId(id) => if id != 0 { Some(id) } else { None },
509 MethodCallKey(_) => None,
512 let (val, fn_ty, must_cast) =
513 monomorphize::monomorphic_fn(ccx, def_id, &substs, opt_ref_id);
514 if must_cast && node != ExprId(0) {
515 // Monotype of the REFERENCE to the function (type params
517 let ref_ty = match node {
518 ExprId(id) => ty::node_id_to_type(tcx, id),
519 MethodCallKey(method_call) => {
520 (*tcx.method_map.borrow())[method_call].ty
523 let ref_ty = monomorphize::apply_param_substs(tcx,
526 let llptrty = type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to();
527 if llptrty != val_ty(val) {
528 let val = consts::ptrcast(val, llptrty);
529 return Datum::new(val, ref_ty, Rvalue::new(ByValue));
532 return Datum::new(val, fn_ty, Rvalue::new(ByValue));
535 // Type scheme of the function item (may have type params)
536 let fn_type_scheme = ty::lookup_item_type(tcx, def_id);
537 let fn_type = monomorphize::normalize_associated_type(tcx, &fn_type_scheme.ty);
539 // Find the actual function pointer.
541 if def_id.krate == ast::LOCAL_CRATE {
542 // Internal reference.
543 get_item_val(ccx, def_id.node)
545 // External reference.
546 trans_external_path(ccx, def_id, fn_type)
550 // This is subtle and surprising, but sometimes we have to bitcast
551 // the resulting fn pointer. The reason has to do with external
552 // functions. If you have two crates that both bind the same C
553 // library, they may not use precisely the same types: for
554 // example, they will probably each declare their own structs,
555 // which are distinct types from LLVM's point of view (nominal
558 // Now, if those two crates are linked into an application, and
559 // they contain inlined code, you can wind up with a situation
560 // where both of those functions wind up being loaded into this
561 // application simultaneously. In that case, the same function
562 // (from LLVM's point of view) requires two types. But of course
563 // LLVM won't allow one function to have two types.
565 // What we currently do, therefore, is declare the function with
566 // one of the two types (whichever happens to come first) and then
567 // bitcast as needed when the function is referenced to make sure
568 // it has the type we expect.
570 // This can occur on either a crate-local or crate-external
571 // reference. It also occurs when testing libcore and in some
572 // other weird situations. Annoying.
573 let llty = type_of::type_of_fn_from_ty(ccx, fn_type);
574 let llptrty = llty.ptr_to();
575 if val_ty(val) != llptrty {
576 debug!("trans_fn_ref_with_vtables(): casting pointer!");
577 val = consts::ptrcast(val, llptrty);
579 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
582 Datum::new(val, fn_type, Rvalue::new(ByValue))
585 // ______________________________________________________________________
588 pub fn trans_call<'a, 'blk, 'tcx>(in_cx: Block<'blk, 'tcx>,
591 args: CallArgs<'a, 'tcx>,
593 -> Block<'blk, 'tcx> {
594 let _icx = push_ctxt("trans_call");
595 trans_call_inner(in_cx,
596 Some(common::expr_info(call_ex)),
597 expr_ty_adjusted(in_cx, f),
598 |cx, _| trans(cx, f),
603 pub fn trans_method_call<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
606 args: CallArgs<'a, 'tcx>,
608 -> Block<'blk, 'tcx> {
609 let _icx = push_ctxt("trans_method_call");
610 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
611 let method_call = MethodCall::expr(call_ex.id);
612 let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
615 Some(common::expr_info(call_ex)),
616 monomorphize_type(bcx, method_ty),
617 |cx, arg_cleanup_scope| {
618 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
624 pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
627 dest: Option<expr::Dest>)
628 -> Result<'blk, 'tcx> {
629 let fty = if did.krate == ast::LOCAL_CRATE {
630 ty::node_id_to_type(bcx.tcx(), did.node)
632 csearch::get_type(bcx.tcx(), did).ty
634 callee::trans_call_inner(bcx,
638 trans_fn_ref_with_substs_to_callee(bcx,
641 subst::Substs::trans_empty())
647 /// This behemoth of a function translates function calls. Unfortunately, in order to generate more
648 /// efficient LLVM output at -O0, it has quite a complex signature (refactoring this into two
649 /// functions seems like a good idea).
651 /// In particular, for lang items, it is invoked with a dest of None, and in that case the return
652 /// value contains the result of the fn. The lang item must not return a structural type or else
653 /// all heck breaks loose.
655 /// For non-lang items, `dest` is always Some, and hence the result is written into memory
656 /// somewhere. Nonetheless we return the actual return value of the function.
657 pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
658 call_info: Option<NodeInfo>,
661 args: CallArgs<'a, 'tcx>,
662 dest: Option<expr::Dest>)
663 -> Result<'blk, 'tcx> where
664 F: FnOnce(Block<'blk, 'tcx>, cleanup::ScopeId) -> Callee<'blk, 'tcx>,
666 // Introduce a temporary cleanup scope that will contain cleanups
667 // for the arguments while they are being evaluated. The purpose
668 // this cleanup is to ensure that, should a panic occur while
669 // evaluating argument N, the values for arguments 0...N-1 are all
670 // cleaned up. If no panic occurs, the values are handed off to
671 // the callee, and hence none of the cleanups in this temporary
672 // scope will ever execute.
675 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
677 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
678 let mut bcx = callee.bcx;
680 let (abi, ret_ty) = match callee_ty.sty {
681 ty::ty_bare_fn(_, ref f) => (f.abi, f.sig.0.output),
682 ty::ty_closure(ref f) => (f.abi, f.sig.0.output),
683 _ => panic!("expected bare rust fn or closure in trans_call_inner")
686 let (llfn, llenv, llself) = match callee.data {
691 (d.llfn, None, Some(d.llself))
694 // Closures are represented as (llfn, llclosure) pair:
695 // load the requisite values out.
696 let pair = d.to_llref();
697 let llfn = GEPi(bcx, pair, &[0u, abi::FAT_PTR_ADDR]);
698 let llfn = Load(bcx, llfn);
699 let llenv = GEPi(bcx, pair, &[0u, abi::FAT_PTR_EXTRA]);
700 let llenv = Load(bcx, llenv);
701 (llfn, Some(llenv), None)
703 Intrinsic(node, substs) => {
704 assert!(abi == synabi::RustIntrinsic);
705 assert!(dest.is_some());
707 let call_info = call_info.expect("no call info for intrinsic call?");
708 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
709 arg_cleanup_scope, args,
710 dest.unwrap(), substs,
713 NamedTupleConstructor(substs, disr) => {
714 assert!(dest.is_some());
715 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
717 let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
718 return base::trans_named_tuple_constructor(bcx,
727 // Intrinsics should not become actual functions.
728 // We trans them in place in `trans_intrinsic_call`
729 assert!(abi != synabi::RustIntrinsic);
731 let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
733 // Generate a location to store the result. If the user does
734 // not care about the result, just make a stack slot.
735 let opt_llretslot = dest.and_then(|dest| match dest {
736 expr::SaveIn(dst) => Some(dst),
738 let ret_ty = match ret_ty {
739 ty::FnConverging(ret_ty) => ret_ty,
740 ty::FnDiverging => ty::mk_nil(ccx.tcx())
743 type_of::return_uses_outptr(ccx, ret_ty) ||
744 type_needs_drop(bcx.tcx(), ret_ty) {
745 // Push the out-pointer if we use an out-pointer for this
746 // return type, otherwise push "undef".
747 if type_is_zero_size(ccx, ret_ty) {
748 let llty = type_of::type_of(ccx, ret_ty);
749 Some(C_undef(llty.ptr_to()))
751 Some(alloc_ty(bcx, ret_ty, "__llret"))
759 let mut llresult = unsafe {
760 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
763 // The code below invokes the function, using either the Rust
764 // conventions (if it is a rust fn) or the native conventions
765 // (otherwise). The important part is that, when all is said
766 // and done, either the return value of the function will have been
767 // written in opt_llretslot (if it is Some) or `llresult` will be
768 // set appropriately (otherwise).
770 let mut llargs = Vec::new();
772 if let (ty::FnConverging(ret_ty), Some(llretslot)) = (ret_ty, opt_llretslot) {
773 if type_of::return_uses_outptr(ccx, ret_ty) {
774 llargs.push(llretslot);
778 // Push the environment (or a trait object's self).
779 match (llenv, llself) {
780 (Some(llenv), None) => llargs.push(llenv),
781 (None, Some(llself)) => llargs.push(llself),
785 // Push the arguments.
786 bcx = trans_args(bcx,
790 cleanup::CustomScope(arg_cleanup_scope),
794 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
796 // Invoke the actual rust fn and update bcx/llresult.
797 let (llret, b) = base::invoke(bcx,
805 // If the Rust convention for this type is return via
806 // the return value, copy it into llretslot.
807 match (opt_llretslot, ret_ty) {
808 (Some(llretslot), ty::FnConverging(ret_ty)) => {
809 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
810 !type_is_zero_size(bcx.ccx(), ret_ty)
812 store_ty(bcx, llret, llretslot, ret_ty)
818 // Lang items are the only case where dest is None, and
819 // they are always Rust fns.
820 assert!(dest.is_some());
822 let mut llargs = Vec::new();
823 let arg_tys = match args {
824 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
825 _ => panic!("expected arg exprs.")
827 bcx = trans_args(bcx,
831 cleanup::CustomScope(arg_cleanup_scope),
834 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
836 bcx = foreign::trans_native_call(bcx, callee_ty,
837 llfn, opt_llretslot.unwrap(),
841 fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_cleanup_scope);
843 // If the caller doesn't care about the result of this fn call,
844 // drop the temporary slot we made.
845 match (dest, opt_llretslot, ret_ty) {
846 (Some(expr::Ignore), Some(llretslot), ty::FnConverging(ret_ty)) => {
847 // drop the value if it is not being saved.
848 bcx = glue::drop_ty(bcx, llretslot, ret_ty, call_info);
849 call_lifetime_end(bcx, llretslot);
854 if ret_ty == ty::FnDiverging {
858 Result::new(bcx, llresult)
861 pub enum CallArgs<'a, 'tcx> {
862 // Supply value of arguments as a list of expressions that must be
863 // translated. This is used in the common case of `foo(bar, qux)`.
864 ArgExprs(&'a [P<ast::Expr>]),
866 // Supply value of arguments as a list of LLVM value refs; frequently
867 // used with lang items and so forth, when the argument is an internal
869 ArgVals(&'a [ValueRef]),
871 // For overloaded operators: `(lhs, Vec(rhs, rhs_id), autoref)`. `lhs`
872 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
873 // the right-hand-side arguments (if any). `autoref` indicates whether the `rhs`
874 // arguments should be auto-referenced
875 ArgOverloadedOp(Datum<'tcx, Expr>, Vec<(Datum<'tcx, Expr>, ast::NodeId)>, bool),
877 // Supply value of arguments as a list of expressions that must be
878 // translated, for overloaded call operators.
879 ArgOverloadedCall(Vec<&'a ast::Expr>),
882 fn trans_args_under_call_abi<'blk, 'tcx>(
883 mut bcx: Block<'blk, 'tcx>,
884 arg_exprs: &[P<ast::Expr>],
886 llargs: &mut Vec<ValueRef>,
887 arg_cleanup_scope: cleanup::ScopeId,
889 -> Block<'blk, 'tcx> {
890 // Translate the `self` argument first.
892 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
893 llargs.push(unpack_result!(bcx, {
895 ty::ty_fn_args(fn_ty)[0],
902 // Now untuple the rest of the arguments.
903 let tuple_expr = &arg_exprs[1];
904 let tuple_type = node_id_type(bcx, tuple_expr.id);
906 match tuple_type.sty {
907 ty::ty_tup(ref field_types) => {
908 let tuple_datum = unpack_datum!(bcx,
909 expr::trans(bcx, &**tuple_expr));
910 let tuple_lvalue_datum =
912 tuple_datum.to_lvalue_datum(bcx,
915 let repr = adt::represent_type(bcx.ccx(), tuple_type);
916 let repr_ptr = &*repr;
917 for i in range(0, field_types.len()) {
918 let arg_datum = tuple_lvalue_datum.get_element(
922 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
924 let arg_datum = arg_datum.to_expr_datum();
926 unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
928 unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
929 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
933 bcx.sess().span_bug(tuple_expr.span,
934 "argument to `.call()` wasn't a tuple?!")
941 fn trans_overloaded_call_args<'blk, 'tcx>(
942 mut bcx: Block<'blk, 'tcx>,
943 arg_exprs: Vec<&ast::Expr>,
945 llargs: &mut Vec<ValueRef>,
946 arg_cleanup_scope: cleanup::ScopeId,
948 -> Block<'blk, 'tcx> {
949 // Translate the `self` argument first.
950 let arg_tys = ty::ty_fn_args(fn_ty);
952 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
953 llargs.push(unpack_result!(bcx, {
962 // Now untuple the rest of the arguments.
963 let tuple_type = arg_tys[1];
964 match tuple_type.sty {
965 ty::ty_tup(ref field_types) => {
966 for (i, &field_type) in field_types.iter().enumerate() {
968 unpack_datum!(bcx, expr::trans(bcx, arg_exprs[i + 1]));
969 llargs.push(unpack_result!(bcx, {
979 bcx.sess().span_bug(arg_exprs[0].span,
980 "argument to `.call()` wasn't a tuple?!")
987 pub fn trans_args<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
988 args: CallArgs<'a, 'tcx>,
990 llargs: &mut Vec<ValueRef>,
991 arg_cleanup_scope: cleanup::ScopeId,
994 -> Block<'blk, 'tcx> {
995 debug!("trans_args(abi={})", abi);
997 let _icx = push_ctxt("trans_args");
998 let arg_tys = ty::ty_fn_args(fn_ty);
999 let variadic = ty::fn_is_variadic(fn_ty);
1003 // First we figure out the caller's view of the types of the arguments.
1004 // This will be needed if this is a generic call, because the callee has
1005 // to cast her view of the arguments to the caller's view.
1007 ArgExprs(arg_exprs) => {
1008 if abi == synabi::RustCall {
1009 // This is only used for direct calls to the `call`,
1010 // `call_mut` or `call_once` functions.
1011 return trans_args_under_call_abi(cx,
1019 let num_formal_args = arg_tys.len();
1020 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1021 if i == 0 && ignore_self {
1024 let arg_ty = if i >= num_formal_args {
1026 expr_ty_adjusted(cx, &**arg_expr)
1031 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1032 llargs.push(unpack_result!(bcx, {
1033 trans_arg_datum(bcx, arg_ty, arg_datum,
1039 ArgOverloadedCall(arg_exprs) => {
1040 return trans_overloaded_call_args(cx,
1047 ArgOverloadedOp(lhs, rhs, autoref) => {
1050 llargs.push(unpack_result!(bcx, {
1051 trans_arg_datum(bcx, arg_tys[0], lhs,
1056 assert_eq!(arg_tys.len(), 1 + rhs.len());
1057 for (rhs, rhs_id) in rhs.into_iter() {
1058 llargs.push(unpack_result!(bcx, {
1059 trans_arg_datum(bcx, arg_tys[1], rhs,
1061 if autoref { DoAutorefArg(rhs_id) } else { DontAutorefArg })
1066 llargs.push_all(vs);
1074 pub enum AutorefArg {
1076 DoAutorefArg(ast::NodeId)
1079 pub fn trans_arg_datum<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1080 formal_arg_ty: Ty<'tcx>,
1081 arg_datum: Datum<'tcx, Expr>,
1082 arg_cleanup_scope: cleanup::ScopeId,
1083 autoref_arg: AutorefArg)
1084 -> Result<'blk, 'tcx> {
1085 let _icx = push_ctxt("trans_arg_datum");
1087 let ccx = bcx.ccx();
1089 debug!("trans_arg_datum({})",
1090 formal_arg_ty.repr(bcx.tcx()));
1092 let arg_datum_ty = arg_datum.ty;
1094 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1097 // FIXME(#3548) use the adjustments table
1099 DoAutorefArg(arg_id) => {
1100 // We will pass argument by reference
1101 // We want an lvalue, so that we can pass by reference and
1102 let arg_datum = unpack_datum!(
1103 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1104 val = arg_datum.val;
1107 // Make this an rvalue, since we are going to be
1108 // passing ownership.
1109 let arg_datum = unpack_datum!(
1110 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1112 // Now that arg_datum is owned, get it into the appropriate
1113 // mode (ref vs value).
1114 let arg_datum = unpack_datum!(
1115 bcx, arg_datum.to_appropriate_datum(bcx));
1117 // Technically, ownership of val passes to the callee.
1118 // However, we must cleanup should we panic before the
1119 // callee is actually invoked.
1120 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1124 if formal_arg_ty != arg_datum_ty {
1125 // this could happen due to e.g. subtyping
1126 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1127 debug!("casting actual type ({}) to match formal ({})",
1128 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1129 debug!("Rust types: {}; {}", ty_to_string(bcx.tcx(), arg_datum_ty),
1130 ty_to_string(bcx.tcx(), formal_arg_ty));
1131 val = PointerCast(bcx, val, llformal_arg_ty);
1134 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1135 Result::new(bcx, val)