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;
25 use llvm::{ValueRef, get_param};
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::typeck::coherence::make_substs_for_receiver_types;
53 use middle::typeck::MethodCall;
54 use util::ppaux::Repr;
55 use util::ppaux::ty_to_string;
57 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:
97 return trans_def(bcx, bcx.def(expr.id), expr);
102 // any other expressions are closures:
103 return datum_callee(bcx, expr);
105 fn datum_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
106 -> Callee<'blk, 'tcx> {
107 let DatumBlock {mut bcx, datum} = expr::trans(bcx, expr);
109 ty::ty_bare_fn(..) => {
110 let llval = datum.to_llscalarish(bcx);
116 ty::ty_closure(..) => {
117 let datum = unpack_datum!(
118 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
121 data: Closure(datum),
125 bcx.tcx().sess.span_bug(
127 format!("type of callee is neither bare-fn nor closure: \
129 bcx.ty_to_string(datum.ty)).as_slice());
134 fn fn_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, llfn: ValueRef)
135 -> Callee<'blk, 'tcx> {
142 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
144 ref_expr: &ast::Expr)
145 -> Callee<'blk, 'tcx> {
146 debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
147 let expr_ty = node_id_type(bcx, ref_expr.id);
149 def::DefFn(did, _) if {
150 let maybe_def_id = inline::get_local_instance(bcx.ccx(), did);
151 let maybe_ast_node = maybe_def_id.and_then(|def_id| bcx.tcx().map
153 match maybe_ast_node {
154 Some(ast_map::NodeStructCtor(_)) => true,
158 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
161 data: NamedTupleConstructor(substs, 0)
164 def::DefFn(did, _) if match expr_ty.sty {
165 ty::ty_bare_fn(ref f) => f.abi == synabi::RustIntrinsic,
168 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
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, did, ExprId(ref_expr.id)))
176 def::DefStaticMethod(meth_did, def::FromTrait(trait_did)) |
177 def::DefMethod(meth_did, _, def::FromTrait(trait_did)) => {
178 fn_callee(bcx, meth::trans_static_method_callee(bcx, meth_did,
182 def::DefVariant(tid, vid, _) => {
183 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
184 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
186 // Nullary variants are not callable
187 assert!(vinfo.args.len() > 0u);
191 data: NamedTupleConstructor(substs, vinfo.disr_val)
194 def::DefStruct(_) => {
195 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
198 data: NamedTupleConstructor(substs, 0)
204 def::DefUpvar(..) => {
205 datum_callee(bcx, ref_expr)
207 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
208 def::DefTy(..) | def::DefPrimTy(..) | def::DefAssociatedTy(..) |
209 def::DefUse(..) | def::DefTyParamBinder(..) |
210 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
211 def::DefSelfTy(..) => {
212 bcx.tcx().sess.span_bug(
214 format!("cannot translate def {} \
215 to a callable thing!", def).as_slice());
221 /// Translates a reference (with id `ref_id`) to the fn/method with id `def_id` into a function
222 /// pointer. This may require monomorphization or inlining.
223 pub fn trans_fn_ref(bcx: Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
224 let _icx = push_ctxt("trans_fn_ref");
226 let substs = node_id_substs(bcx, node);
227 debug!("trans_fn_ref(def_id={}, node={}, substs={})",
228 def_id.repr(bcx.tcx()),
230 substs.repr(bcx.tcx()));
231 trans_fn_ref_with_substs(bcx, def_id, node, substs)
234 fn trans_fn_ref_with_substs_to_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
237 substs: subst::Substs<'tcx>)
238 -> Callee<'blk, 'tcx> {
241 data: Fn(trans_fn_ref_with_substs(bcx,
248 /// Translates the adapter that deconstructs a `Box<Trait>` object into
249 /// `Trait` so that a by-value self method can be called.
250 pub fn trans_unboxing_shim<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
251 llshimmedfn: ValueRef,
252 fty: &ty::BareFnTy<'tcx>,
253 method_id: ast::DefId,
254 substs: &subst::Substs<'tcx>)
256 let _icx = push_ctxt("trans_unboxing_shim");
260 let fty = fty.subst(tcx, substs);
262 // Transform the self type to `Box<self_type>`.
263 let self_type = fty.sig.inputs[0];
264 let boxed_self_type = ty::mk_uniq(tcx, self_type);
265 let boxed_function_type = ty::FnSig {
266 inputs: fty.sig.inputs.iter().enumerate().map(|(i, typ)| {
273 output: fty.sig.output,
276 let boxed_function_type = ty::BareFnTy {
277 fn_style: fty.fn_style,
279 sig: boxed_function_type,
281 let boxed_function_type = ty::mk_bare_fn(tcx, boxed_function_type);
282 let function_type = match fty.abi {
283 synabi::RustCall => {
284 // We're passing through to a RustCall ABI function, but
285 // because the shim will already perform untupling, we
286 // need to pretend the shimmed function does not use
287 // RustCall so the untupled arguments can be passed
288 // through verbatim. This is kind of ugly.
289 let fake_ty = ty::FnSig {
290 inputs: type_of::untuple_arguments_if_necessary(ccx,
291 fty.sig.inputs.as_slice(),
293 output: fty.sig.output,
296 let fake_ty = ty::BareFnTy {
297 fn_style: fty.fn_style,
301 ty::mk_bare_fn(tcx, fake_ty)
304 ty::mk_bare_fn(tcx, fty)
308 let function_name = ty::with_path(tcx, method_id, |path| {
309 link::mangle_internal_name_by_path_and_seq(path, "unboxing_shim")
311 let llfn = decl_internal_rust_fn(ccx,
313 function_name.as_slice());
315 let block_arena = TypedArena::new();
316 let empty_param_substs = Substs::trans_empty();
317 let return_type = ty::ty_fn_ret(boxed_function_type);
318 let fcx = new_fn_ctxt(ccx,
326 let mut bcx = init_function(&fcx, false, return_type);
328 // Create the substituted versions of the self type.
329 let arg_scope = fcx.push_custom_cleanup_scope();
330 let arg_scope_id = cleanup::CustomScope(arg_scope);
331 let boxed_self_type = ty::ty_fn_args(boxed_function_type)[0];
332 let arg_types = ty::ty_fn_args(function_type);
333 let self_type = arg_types[0];
334 let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
336 // Create a datum for self.
337 let llboxedself = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
338 let llboxedself = Datum::new(llboxedself,
343 llboxedself.to_lvalue_datum_in_scope(bcx,
347 // This `Load` is needed because lvalue data are always by-ref.
348 let llboxedself = Load(bcx, boxed_self.val);
350 let llself = if type_is_immediate(ccx, self_type) {
351 let llboxedself = Load(bcx, llboxedself);
352 immediate_rvalue(llboxedself, self_type)
354 let llself = rvalue_scratch_datum(bcx, self_type, "self");
355 memcpy_ty(bcx, llself.val, llboxedself, self_type);
359 // Make sure we don't free the box twice!
360 boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type);
362 // Schedule a cleanup to free the box.
363 fcx.schedule_free_value(arg_scope_id,
365 cleanup::HeapExchange,
368 // Now call the function.
369 let mut llshimmedargs = vec!(llself.val);
370 for i in range(1, arg_types.len()) {
371 llshimmedargs.push(get_param(fcx.llfn, fcx.arg_pos(i) as u32));
373 assert!(!fcx.needs_ret_allocas);
374 let dest = fcx.llretslotptr.get().map(|_|
375 expr::SaveIn(fcx.get_ret_slot(bcx, return_type, "ret_slot"))
377 bcx = trans_call_inner(bcx,
383 data: Fn(llshimmedfn),
386 ArgVals(llshimmedargs.as_slice()),
389 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
390 finish_fn(&fcx, bcx, return_type);
395 /// Translates a reference to a fn/method item, monomorphizing and
396 /// inlining as it goes.
400 /// - `bcx`: the current block where the reference to the fn occurs
401 /// - `def_id`: def id of the fn or method item being referenced
402 /// - `node`: node id of the reference to the fn/method, if applicable.
403 /// This parameter may be zero; but, if so, the resulting value may not
404 /// have the right type, so it must be cast before being used.
405 /// - `substs`: values for each of the fn/method's parameters
406 pub fn trans_fn_ref_with_substs<'blk, 'tcx>(
407 bcx: Block<'blk, 'tcx>, //
408 def_id: ast::DefId, // def id of fn
409 node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
410 substs: subst::Substs<'tcx>) // vtables for the call
413 let _icx = push_ctxt("trans_fn_ref_with_substs");
417 debug!("trans_fn_ref_with_substs(bcx={}, def_id={}, node={}, \
424 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
425 assert!(substs.types.all(|t| !ty::type_has_escaping_regions(*t)));
426 let substs = substs.erase_regions();
428 // Load the info for the appropriate trait if necessary.
429 match ty::trait_of_item(tcx, def_id) {
432 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
436 // We need to do a bunch of special handling for default methods.
437 // We need to modify the def_id and our substs in order to monomorphize
439 let (is_default, def_id, substs) = match ty::provided_source(tcx, def_id) {
440 None => (false, def_id, substs),
442 // There are two relevant substitutions when compiling
443 // default methods. First, there is the substitution for
444 // the type parameters of the impl we are using and the
445 // method we are calling. This substitution is the substs
446 // argument we already have.
447 // In order to compile a default method, though, we need
448 // to consider another substitution: the substitution for
449 // the type parameters on trait; the impl we are using
450 // implements the trait at some particular type
451 // parameters, and we need to substitute for those first.
452 // So, what we need to do is find this substitution and
453 // compose it with the one we already have.
455 let impl_id = ty::impl_or_trait_item(tcx, def_id).container()
457 let impl_or_trait_item = ty::impl_or_trait_item(tcx, source_id);
458 match impl_or_trait_item {
459 ty::MethodTraitItem(method) => {
460 let trait_ref = ty::impl_trait_ref(tcx, impl_id).unwrap();
461 let trait_ref = ty::erase_late_bound_regions(tcx, &trait_ref);
463 // Compute the first substitution
465 make_substs_for_receiver_types(tcx, &*trait_ref, &*method)
469 let new_substs = first_subst.subst(tcx, &substs);
471 debug!("trans_fn_with_vtables - default method: \
472 substs = {}, trait_subst = {}, \
473 first_subst = {}, new_subst = {}",
474 substs.repr(tcx), trait_ref.substs.repr(tcx),
475 first_subst.repr(tcx), new_substs.repr(tcx));
477 (true, source_id, new_substs)
479 ty::TypeTraitItem(_) => {
480 bcx.tcx().sess.bug("trans_fn_ref_with_vtables() tried \
481 to translate an associated type?!")
487 // If this is an unboxed closure, redirect to it.
488 match closure::get_or_create_declaration_if_unboxed_closure(bcx,
492 Some(llfn) => return llfn,
495 // Check whether this fn has an inlined copy and, if so, redirect
496 // def_id to the local id of the inlined copy.
497 let def_id = inline::maybe_instantiate_inline(ccx, def_id);
499 // We must monomorphise if the fn has type parameters, is a default method,
500 // or is a named tuple constructor.
501 let must_monomorphise = if !substs.types.is_empty() || is_default {
503 } else if def_id.krate == ast::LOCAL_CRATE {
504 let map_node = session::expect(
506 tcx.map.find(def_id.node),
507 || "local item should be in ast map".to_string());
510 ast_map::NodeVariant(v) => match v.node.kind {
511 ast::TupleVariantKind(ref args) => args.len() > 0,
514 ast_map::NodeStructCtor(_) => true,
521 // Create a monomorphic version of generic functions
522 if must_monomorphise {
523 // Should be either intra-crate or inlined.
524 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
526 let opt_ref_id = match node {
527 ExprId(id) => if id != 0 { Some(id) } else { None },
528 MethodCall(_) => None,
531 let (val, must_cast) =
532 monomorphize::monomorphic_fn(ccx, def_id, &substs, opt_ref_id);
534 if must_cast && node != ExprId(0) {
535 // Monotype of the REFERENCE to the function (type params
537 let ref_ty = match node {
538 ExprId(id) => node_id_type(bcx, id),
539 MethodCall(method_call) => {
540 let t = (*bcx.tcx().method_map.borrow())[method_call].ty;
541 monomorphize_type(bcx, t)
546 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
551 // Polytype of the function item (may have type params)
552 let fn_tpt = ty::lookup_item_type(tcx, def_id);
554 // Find the actual function pointer.
556 if def_id.krate == ast::LOCAL_CRATE {
557 // Internal reference.
558 get_item_val(ccx, def_id.node)
560 // External reference.
561 trans_external_path(ccx, def_id, fn_tpt.ty)
565 // This is subtle and surprising, but sometimes we have to bitcast
566 // the resulting fn pointer. The reason has to do with external
567 // functions. If you have two crates that both bind the same C
568 // library, they may not use precisely the same types: for
569 // example, they will probably each declare their own structs,
570 // which are distinct types from LLVM's point of view (nominal
573 // Now, if those two crates are linked into an application, and
574 // they contain inlined code, you can wind up with a situation
575 // where both of those functions wind up being loaded into this
576 // application simultaneously. In that case, the same function
577 // (from LLVM's point of view) requires two types. But of course
578 // LLVM won't allow one function to have two types.
580 // What we currently do, therefore, is declare the function with
581 // one of the two types (whichever happens to come first) and then
582 // bitcast as needed when the function is referenced to make sure
583 // it has the type we expect.
585 // This can occur on either a crate-local or crate-external
586 // reference. It also occurs when testing libcore and in some
587 // other weird situations. Annoying.
588 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
589 let llptrty = llty.ptr_to();
590 if val_ty(val) != llptrty {
591 debug!("trans_fn_ref_with_vtables(): casting pointer!");
592 val = BitCast(bcx, val, llptrty);
594 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
600 // ______________________________________________________________________
603 pub fn trans_call<'a, 'blk, 'tcx>(in_cx: Block<'blk, 'tcx>,
606 args: CallArgs<'a, 'tcx>,
608 -> Block<'blk, 'tcx> {
609 let _icx = push_ctxt("trans_call");
610 trans_call_inner(in_cx,
611 Some(common::expr_info(call_ex)),
613 |cx, _| trans(cx, f),
618 pub fn trans_method_call<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
621 args: CallArgs<'a, 'tcx>,
623 -> Block<'blk, 'tcx> {
624 let _icx = push_ctxt("trans_method_call");
625 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
626 let method_call = MethodCall::expr(call_ex.id);
627 let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
630 Some(common::expr_info(call_ex)),
631 monomorphize_type(bcx, method_ty),
632 |cx, arg_cleanup_scope| {
633 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
639 pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
642 dest: Option<expr::Dest>)
643 -> Result<'blk, 'tcx> {
644 let fty = if did.krate == ast::LOCAL_CRATE {
645 ty::node_id_to_type(bcx.tcx(), did.node)
647 csearch::get_type(bcx.tcx(), did).ty
649 callee::trans_call_inner(bcx,
653 trans_fn_ref_with_substs_to_callee(bcx,
656 subst::Substs::trans_empty())
662 /// This behemoth of a function translates function calls. Unfortunately, in order to generate more
663 /// efficient LLVM output at -O0, it has quite a complex signature (refactoring this into two
664 /// functions seems like a good idea).
666 /// In particular, for lang items, it is invoked with a dest of None, and in that case the return
667 /// value contains the result of the fn. The lang item must not return a structural type or else
668 /// all heck breaks loose.
670 /// For non-lang items, `dest` is always Some, and hence the result is written into memory
671 /// somewhere. Nonetheless we return the actual return value of the function.
672 pub fn trans_call_inner<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
673 call_info: Option<NodeInfo>,
675 get_callee: |bcx: Block<'blk, 'tcx>,
676 arg_cleanup_scope: cleanup::ScopeId|
677 -> Callee<'blk, 'tcx>,
678 args: CallArgs<'a, 'tcx>,
679 dest: Option<expr::Dest>)
680 -> Result<'blk, 'tcx> {
681 // Introduce a temporary cleanup scope that will contain cleanups
682 // for the arguments while they are being evaluated. The purpose
683 // this cleanup is to ensure that, should a panic occur while
684 // evaluating argument N, the values for arguments 0...N-1 are all
685 // cleaned up. If no panic occurs, the values are handed off to
686 // the callee, and hence none of the cleanups in this temporary
687 // scope will ever execute.
690 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
692 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
693 let mut bcx = callee.bcx;
695 let (abi, ret_ty) = match callee_ty.sty {
696 ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
697 ty::ty_closure(ref f) => (f.abi, f.sig.output),
698 _ => panic!("expected bare rust fn or closure in trans_call_inner")
701 let (llfn, llenv, llself) = match callee.data {
706 (d.llfn, None, Some(d.llself))
709 // Closures are represented as (llfn, llclosure) pair:
710 // load the requisite values out.
711 let pair = d.to_llref();
712 let llfn = GEPi(bcx, pair, &[0u, abi::FAT_PTR_ADDR]);
713 let llfn = Load(bcx, llfn);
714 let llenv = GEPi(bcx, pair, &[0u, abi::FAT_PTR_EXTRA]);
715 let llenv = Load(bcx, llenv);
716 (llfn, Some(llenv), None)
718 Intrinsic(node, substs) => {
719 assert!(abi == synabi::RustIntrinsic);
720 assert!(dest.is_some());
722 let call_info = call_info.expect("no call info for intrinsic call?");
723 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
724 arg_cleanup_scope, args,
725 dest.unwrap(), substs,
728 NamedTupleConstructor(substs, disr) => {
729 assert!(dest.is_some());
730 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
732 let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
733 return base::trans_named_tuple_constructor(bcx,
742 // Intrinsics should not become actual functions.
743 // We trans them in place in `trans_intrinsic_call`
744 assert!(abi != synabi::RustIntrinsic);
746 let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
748 // Generate a location to store the result. If the user does
749 // not care about the result, just make a stack slot.
750 let opt_llretslot = dest.and_then(|dest| match dest {
751 expr::SaveIn(dst) => Some(dst),
753 let ret_ty = match ret_ty {
754 ty::FnConverging(ret_ty) => ret_ty,
755 ty::FnDiverging => ty::mk_nil(ccx.tcx())
758 type_of::return_uses_outptr(ccx, ret_ty) ||
759 ty::type_needs_drop(bcx.tcx(), ret_ty) {
760 // Push the out-pointer if we use an out-pointer for this
761 // return type, otherwise push "undef".
762 if type_is_zero_size(ccx, ret_ty) {
763 let llty = type_of::type_of(ccx, ret_ty);
764 Some(C_undef(llty.ptr_to()))
766 Some(alloc_ty(bcx, ret_ty, "__llret"))
774 let mut llresult = unsafe {
775 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
778 // The code below invokes the function, using either the Rust
779 // conventions (if it is a rust fn) or the native conventions
780 // (otherwise). The important part is that, when all is said
781 // and done, either the return value of the function will have been
782 // written in opt_llretslot (if it is Some) or `llresult` will be
783 // set appropriately (otherwise).
785 let mut llargs = Vec::new();
787 if let (ty::FnConverging(ret_ty), Some(llretslot)) = (ret_ty, opt_llretslot) {
788 if type_of::return_uses_outptr(ccx, ret_ty) {
789 llargs.push(llretslot);
793 // Push the environment (or a trait object's self).
794 match (llenv, llself) {
795 (Some(llenv), None) => llargs.push(llenv),
796 (None, Some(llself)) => llargs.push(llself),
800 // Push the arguments.
801 bcx = trans_args(bcx,
805 cleanup::CustomScope(arg_cleanup_scope),
809 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
811 // Invoke the actual rust fn and update bcx/llresult.
812 let (llret, b) = base::invoke(bcx,
821 // If the Rust convention for this type is return via
822 // the return value, copy it into llretslot.
823 match (opt_llretslot, ret_ty) {
824 (Some(llretslot), ty::FnConverging(ret_ty)) => {
825 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
826 !type_is_zero_size(bcx.ccx(), ret_ty)
828 store_ty(bcx, llret, llretslot, ret_ty)
834 // Lang items are the only case where dest is None, and
835 // they are always Rust fns.
836 assert!(dest.is_some());
838 let mut llargs = Vec::new();
839 let arg_tys = match args {
840 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
841 _ => panic!("expected arg exprs.")
843 bcx = trans_args(bcx,
847 cleanup::CustomScope(arg_cleanup_scope),
850 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
852 bcx = foreign::trans_native_call(bcx, callee_ty,
853 llfn, opt_llretslot.unwrap(),
854 llargs.as_slice(), arg_tys);
857 fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_cleanup_scope);
859 // If the caller doesn't care about the result of this fn call,
860 // drop the temporary slot we made.
861 match (dest, opt_llretslot, ret_ty) {
862 (Some(expr::Ignore), Some(llretslot), ty::FnConverging(ret_ty)) => {
863 // drop the value if it is not being saved.
864 bcx = glue::drop_ty(bcx, llretslot, ret_ty, call_info);
865 call_lifetime_end(bcx, llretslot);
870 if ret_ty == ty::FnDiverging {
874 Result::new(bcx, llresult)
877 pub enum CallArgs<'a, 'tcx> {
878 // Supply value of arguments as a list of expressions that must be
879 // translated. This is used in the common case of `foo(bar, qux)`.
880 ArgExprs(&'a [P<ast::Expr>]),
882 // Supply value of arguments as a list of LLVM value refs; frequently
883 // used with lang items and so forth, when the argument is an internal
885 ArgVals(&'a [ValueRef]),
887 // For overloaded operators: `(lhs, Vec(rhs, rhs_id))`. `lhs`
888 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
889 // the right-hand-side arguments (if any).
890 ArgOverloadedOp(Datum<'tcx, Expr>, Vec<(Datum<'tcx, Expr>, ast::NodeId)>),
892 // Supply value of arguments as a list of expressions that must be
893 // translated, for overloaded call operators.
894 ArgOverloadedCall(Vec<&'a ast::Expr>),
897 fn trans_args_under_call_abi<'blk, 'tcx>(
898 mut bcx: Block<'blk, 'tcx>,
899 arg_exprs: &[P<ast::Expr>],
901 llargs: &mut Vec<ValueRef>,
902 arg_cleanup_scope: cleanup::ScopeId,
904 -> Block<'blk, 'tcx> {
905 // Translate the `self` argument first.
907 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
908 llargs.push(unpack_result!(bcx, {
910 ty::ty_fn_args(fn_ty)[0],
917 // Now untuple the rest of the arguments.
918 let tuple_expr = &arg_exprs[1];
919 let tuple_type = node_id_type(bcx, tuple_expr.id);
921 match tuple_type.sty {
922 ty::ty_tup(ref field_types) => {
923 let tuple_datum = unpack_datum!(bcx,
924 expr::trans(bcx, &**tuple_expr));
925 let tuple_lvalue_datum =
927 tuple_datum.to_lvalue_datum(bcx,
930 let repr = adt::represent_type(bcx.ccx(), tuple_type);
931 let repr_ptr = &*repr;
932 for i in range(0, field_types.len()) {
933 let arg_datum = tuple_lvalue_datum.get_element(
937 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
939 let arg_datum = arg_datum.to_expr_datum();
941 unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
943 unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
944 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
948 bcx.sess().span_bug(tuple_expr.span,
949 "argument to `.call()` wasn't a tuple?!")
956 fn trans_overloaded_call_args<'blk, 'tcx>(
957 mut bcx: Block<'blk, 'tcx>,
958 arg_exprs: Vec<&ast::Expr>,
960 llargs: &mut Vec<ValueRef>,
961 arg_cleanup_scope: cleanup::ScopeId,
963 -> Block<'blk, 'tcx> {
964 // Translate the `self` argument first.
965 let arg_tys = ty::ty_fn_args(fn_ty);
967 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
968 llargs.push(unpack_result!(bcx, {
977 // Now untuple the rest of the arguments.
978 let tuple_type = arg_tys[1];
979 match tuple_type.sty {
980 ty::ty_tup(ref field_types) => {
981 for (i, &field_type) in field_types.iter().enumerate() {
983 unpack_datum!(bcx, expr::trans(bcx, arg_exprs[i + 1]));
984 llargs.push(unpack_result!(bcx, {
994 bcx.sess().span_bug(arg_exprs[0].span,
995 "argument to `.call()` wasn't a tuple?!")
1002 pub fn trans_args<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
1003 args: CallArgs<'a, 'tcx>,
1005 llargs: &mut Vec<ValueRef>,
1006 arg_cleanup_scope: cleanup::ScopeId,
1009 -> Block<'blk, 'tcx> {
1010 debug!("trans_args(abi={})", abi);
1012 let _icx = push_ctxt("trans_args");
1013 let arg_tys = ty::ty_fn_args(fn_ty);
1014 let variadic = ty::fn_is_variadic(fn_ty);
1018 // First we figure out the caller's view of the types of the arguments.
1019 // This will be needed if this is a generic call, because the callee has
1020 // to cast her view of the arguments to the caller's view.
1022 ArgExprs(arg_exprs) => {
1023 if abi == synabi::RustCall {
1024 // This is only used for direct calls to the `call`,
1025 // `call_mut` or `call_once` functions.
1026 return trans_args_under_call_abi(cx,
1034 let num_formal_args = arg_tys.len();
1035 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1036 if i == 0 && ignore_self {
1039 let arg_ty = if i >= num_formal_args {
1041 expr_ty_adjusted(cx, &**arg_expr)
1046 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1047 llargs.push(unpack_result!(bcx, {
1048 trans_arg_datum(bcx, arg_ty, arg_datum,
1054 ArgOverloadedCall(arg_exprs) => {
1055 return trans_overloaded_call_args(cx,
1062 ArgOverloadedOp(lhs, rhs) => {
1065 llargs.push(unpack_result!(bcx, {
1066 trans_arg_datum(bcx, arg_tys[0], lhs,
1071 assert_eq!(arg_tys.len(), 1 + rhs.len());
1072 for (rhs, rhs_id) in rhs.into_iter() {
1073 llargs.push(unpack_result!(bcx, {
1074 trans_arg_datum(bcx, arg_tys[1], rhs,
1076 DoAutorefArg(rhs_id))
1081 llargs.push_all(vs);
1088 pub enum AutorefArg {
1090 DoAutorefArg(ast::NodeId)
1093 pub fn trans_arg_datum<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1094 formal_arg_ty: Ty<'tcx>,
1095 arg_datum: Datum<'tcx, Expr>,
1096 arg_cleanup_scope: cleanup::ScopeId,
1097 autoref_arg: AutorefArg)
1098 -> Result<'blk, 'tcx> {
1099 let _icx = push_ctxt("trans_arg_datum");
1101 let ccx = bcx.ccx();
1103 debug!("trans_arg_datum({})",
1104 formal_arg_ty.repr(bcx.tcx()));
1106 let arg_datum_ty = arg_datum.ty;
1108 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1111 // FIXME(#3548) use the adjustments table
1113 DoAutorefArg(arg_id) => {
1114 // We will pass argument by reference
1115 // We want an lvalue, so that we can pass by reference and
1116 let arg_datum = unpack_datum!(
1117 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1118 val = arg_datum.val;
1121 // Make this an rvalue, since we are going to be
1122 // passing ownership.
1123 let arg_datum = unpack_datum!(
1124 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1126 // Now that arg_datum is owned, get it into the appropriate
1127 // mode (ref vs value).
1128 let arg_datum = unpack_datum!(
1129 bcx, arg_datum.to_appropriate_datum(bcx));
1131 // Technically, ownership of val passes to the callee.
1132 // However, we must cleanup should we panic before the
1133 // callee is actually invoked.
1134 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1138 if formal_arg_ty != arg_datum_ty {
1139 // this could happen due to e.g. subtyping
1140 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1141 debug!("casting actual type ({}) to match formal ({})",
1142 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1143 debug!("Rust types: {}; {}", ty_to_string(bcx.tcx(), arg_datum_ty),
1144 ty_to_string(bcx.tcx(), formal_arg_ty));
1145 val = PointerCast(bcx, val, llformal_arg_ty);
1148 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1149 Result::new(bcx, val)