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.
12 * Handles translation of callees as well as other call-related
13 * things. Callees are a superset of normal rust values and sometimes
14 * have different representations. In particular, top-level fn items
15 * and methods are represented as just a fn ptr and not a full
19 use arena::TypedArena;
23 use llvm::{ValueRef, get_param};
25 use metadata::csearch;
28 use middle::subst::{Subst};
29 use middle::trans::adt;
30 use middle::trans::base;
31 use middle::trans::base::*;
32 use middle::trans::build::*;
33 use middle::trans::callee;
34 use middle::trans::cleanup;
35 use middle::trans::cleanup::CleanupMethods;
36 use middle::trans::closure;
37 use middle::trans::common;
38 use middle::trans::common::*;
39 use middle::trans::datum::*;
40 use middle::trans::expr;
41 use middle::trans::glue;
42 use middle::trans::inline;
43 use middle::trans::foreign;
44 use middle::trans::intrinsic;
45 use middle::trans::meth;
46 use middle::trans::monomorphize;
47 use middle::trans::type_::Type;
48 use middle::trans::type_of;
50 use middle::typeck::coherence::make_substs_for_receiver_types;
51 use middle::typeck::MethodCall;
52 use util::ppaux::Repr;
53 use util::ppaux::ty_to_string;
55 use syntax::abi as synabi;
60 pub struct MethodData {
66 Closure(Datum<Lvalue>),
68 // Constructor for enum variant/tuple-like-struct
70 NamedTupleConstructor(subst::Substs, 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),
82 pub struct Callee<'blk, 'tcx: 'blk> {
83 pub bcx: Block<'blk, 'tcx>,
87 fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
88 -> Callee<'blk, 'tcx> {
89 let _icx = push_ctxt("trans_callee");
90 debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
92 // pick out special kinds of expressions that can be called:
95 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);
106 match ty::get(datum.ty).sty {
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)).as_slice());
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, ExprId(ref_expr.id));
159 data: NamedTupleConstructor(substs, 0)
162 def::DefFn(did, _) if match ty::get(expr_ty).sty {
163 ty::ty_bare_fn(ref f) => f.abi == synabi::RustIntrinsic,
166 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
167 let def_id = inline::maybe_instantiate_inline(bcx.ccx(), did);
168 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
170 def::DefFn(did, _) | def::DefMethod(did, _, def::FromImpl(_)) |
171 def::DefStaticMethod(did, def::FromImpl(_)) => {
172 fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
174 def::DefStaticMethod(meth_did, def::FromTrait(trait_did)) |
175 def::DefMethod(meth_did, _, def::FromTrait(trait_did)) => {
176 fn_callee(bcx, meth::trans_static_method_callee(bcx, meth_did,
180 def::DefVariant(tid, vid, _) => {
181 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
182 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
184 // Nullary variants are not callable
185 assert!(vinfo.args.len() > 0u);
189 data: NamedTupleConstructor(substs, vinfo.disr_val)
192 def::DefStruct(_) => {
193 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
196 data: NamedTupleConstructor(substs, 0)
202 def::DefUpvar(..) => {
203 datum_callee(bcx, ref_expr)
205 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
206 def::DefTy(..) | def::DefPrimTy(..) | def::DefAssociatedTy(..) |
207 def::DefUse(..) | def::DefTyParamBinder(..) |
208 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
209 def::DefSelfTy(..) => {
210 bcx.tcx().sess.span_bug(
212 format!("cannot translate def {} \
213 to a callable thing!", def).as_slice());
219 pub fn trans_fn_ref(bcx: Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
221 * Translates a reference (with id `ref_id`) to the fn/method
222 * with id `def_id` into a function pointer. This may require
223 * monomorphization or inlining.
226 let _icx = push_ctxt("trans_fn_ref");
228 let substs = node_id_substs(bcx, node);
229 debug!("trans_fn_ref(def_id={}, node={}, substs={})",
230 def_id.repr(bcx.tcx()),
232 substs.repr(bcx.tcx()));
233 trans_fn_ref_with_substs(bcx, def_id, node, substs)
236 fn trans_fn_ref_with_substs_to_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
239 substs: subst::Substs)
240 -> Callee<'blk, 'tcx> {
243 data: Fn(trans_fn_ref_with_substs(bcx,
250 /// Translates the adapter that deconstructs a `Box<Trait>` object into
251 /// `Trait` so that a by-value self method can be called.
252 pub fn trans_unboxing_shim(bcx: Block,
253 llshimmedfn: ValueRef,
255 method_id: ast::DefId,
256 substs: &subst::Substs)
258 let _icx = push_ctxt("trans_unboxing_shim");
262 let fty = fty.subst(tcx, substs);
264 // Transform the self type to `Box<self_type>`.
265 let self_type = fty.sig.inputs[0];
266 let boxed_self_type = ty::mk_uniq(tcx, self_type);
267 let boxed_function_type = ty::FnSig {
268 binder_id: fty.sig.binder_id,
269 inputs: fty.sig.inputs.iter().enumerate().map(|(i, typ)| {
276 output: fty.sig.output,
279 let boxed_function_type = ty::BareFnTy {
280 fn_style: fty.fn_style,
282 sig: boxed_function_type,
284 let boxed_function_type = ty::mk_bare_fn(tcx, boxed_function_type);
285 let function_type = match fty.abi {
286 synabi::RustCall => {
287 // We're passing through to a RustCall ABI function, but
288 // because the shim will already perform untupling, we
289 // need to pretend the shimmed function does not use
290 // RustCall so the untupled arguments can be passed
291 // through verbatim. This is kind of ugly.
292 let fake_ty = ty::FnSig {
293 binder_id: fty.sig.binder_id,
294 inputs: type_of::untuple_arguments_if_necessary(ccx,
295 fty.sig.inputs.as_slice(),
297 output: fty.sig.output,
300 let fake_ty = ty::BareFnTy {
301 fn_style: fty.fn_style,
305 ty::mk_bare_fn(tcx, fake_ty)
308 ty::mk_bare_fn(tcx, fty)
312 let function_name = ty::with_path(tcx, method_id, |path| {
313 link::mangle_internal_name_by_path_and_seq(path, "unboxing_shim")
315 let llfn = decl_internal_rust_fn(ccx,
317 function_name.as_slice());
319 let block_arena = TypedArena::new();
320 let empty_param_substs = param_substs::empty();
321 let return_type = ty::ty_fn_ret(boxed_function_type);
322 let fcx = new_fn_ctxt(ccx,
330 let mut bcx = init_function(&fcx, false, return_type);
332 // Create the substituted versions of the self type.
333 let arg_scope = fcx.push_custom_cleanup_scope();
334 let arg_scope_id = cleanup::CustomScope(arg_scope);
335 let boxed_arg_types = ty::ty_fn_args(boxed_function_type);
336 let boxed_self_type = boxed_arg_types[0];
337 let arg_types = ty::ty_fn_args(function_type);
338 let self_type = arg_types[0];
339 let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
341 // Create a datum for self.
342 let llboxedself = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
343 let llboxedself = Datum::new(llboxedself,
348 llboxedself.to_lvalue_datum_in_scope(bcx,
352 // This `Load` is needed because lvalue data are always by-ref.
353 let llboxedself = Load(bcx, boxed_self.val);
355 let llself = if type_is_immediate(ccx, self_type) {
356 let llboxedself = Load(bcx, llboxedself);
357 immediate_rvalue(llboxedself, self_type)
359 let llself = rvalue_scratch_datum(bcx, self_type, "self");
360 memcpy_ty(bcx, llself.val, llboxedself, self_type);
364 // Make sure we don't free the box twice!
365 boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type);
367 // Schedule a cleanup to free the box.
368 fcx.schedule_free_value(arg_scope_id,
370 cleanup::HeapExchange,
373 // Now call the function.
374 let mut llshimmedargs = vec!(llself.val);
375 for i in range(1, arg_types.len()) {
376 llshimmedargs.push(get_param(fcx.llfn, fcx.arg_pos(i) as u32));
378 assert!(!fcx.needs_ret_allocas);
379 let dest = fcx.llretslotptr.get().map(|_|
380 expr::SaveIn(fcx.get_ret_slot(bcx, return_type, "ret_slot"))
382 bcx = trans_call_inner(bcx,
388 data: Fn(llshimmedfn),
391 ArgVals(llshimmedargs.as_slice()),
394 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
395 finish_fn(&fcx, bcx, return_type);
400 pub fn trans_fn_ref_with_substs(
402 def_id: ast::DefId, // def id of fn
403 node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
404 substs: subst::Substs) // vtables for the call
408 * Translates a reference to a fn/method item, monomorphizing and
409 * inlining as it goes.
413 * - `bcx`: the current block where the reference to the fn occurs
414 * - `def_id`: def id of the fn or method item being referenced
415 * - `node`: node id of the reference to the fn/method, if applicable.
416 * This parameter may be zero; but, if so, the resulting value may not
417 * have the right type, so it must be cast before being used.
418 * - `substs`: values for each of the fn/method's parameters
421 let _icx = push_ctxt("trans_fn_ref_with_substs");
425 debug!("trans_fn_ref_with_substs(bcx={}, def_id={}, node={}, \
432 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
434 // Load the info for the appropriate trait if necessary.
435 match ty::trait_of_item(tcx, def_id) {
438 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
442 // We need to do a bunch of special handling for default methods.
443 // We need to modify the def_id and our substs in order to monomorphize
445 let (is_default, def_id, substs) = match ty::provided_source(tcx, def_id) {
446 None => (false, def_id, substs),
448 // There are two relevant substitutions when compiling
449 // default methods. First, there is the substitution for
450 // the type parameters of the impl we are using and the
451 // method we are calling. This substitution is the substs
452 // argument we already have.
453 // In order to compile a default method, though, we need
454 // to consider another substitution: the substitution for
455 // the type parameters on trait; the impl we are using
456 // implements the trait at some particular type
457 // parameters, and we need to substitute for those first.
458 // So, what we need to do is find this substitution and
459 // compose it with the one we already have.
461 let impl_id = ty::impl_or_trait_item(tcx, def_id).container()
463 let impl_or_trait_item = ty::impl_or_trait_item(tcx, source_id);
464 match impl_or_trait_item {
465 ty::MethodTraitItem(method) => {
466 let trait_ref = ty::impl_trait_ref(tcx, impl_id)
467 .expect("could not find trait_ref for impl with \
470 // Compute the first substitution
471 let first_subst = make_substs_for_receiver_types(
472 tcx, &*trait_ref, &*method);
475 let new_substs = first_subst.subst(tcx, &substs);
477 debug!("trans_fn_with_vtables - default method: \
478 substs = {}, trait_subst = {}, \
479 first_subst = {}, new_subst = {}",
480 substs.repr(tcx), trait_ref.substs.repr(tcx),
481 first_subst.repr(tcx), new_substs.repr(tcx));
483 (true, source_id, new_substs)
485 ty::TypeTraitItem(_) => {
486 bcx.tcx().sess.bug("trans_fn_ref_with_vtables() tried \
487 to translate an associated type?!")
493 // If this is an unboxed closure, redirect to it.
494 match closure::get_or_create_declaration_if_unboxed_closure(bcx,
498 Some(llfn) => return llfn,
501 // Check whether this fn has an inlined copy and, if so, redirect
502 // def_id to the local id of the inlined copy.
503 let def_id = inline::maybe_instantiate_inline(ccx, def_id);
505 // We must monomorphise if the fn has type parameters, is a default method,
506 // or is a named tuple constructor.
507 let must_monomorphise = if !substs.types.is_empty() || is_default {
509 } else if def_id.krate == ast::LOCAL_CRATE {
510 let map_node = session::expect(
512 tcx.map.find(def_id.node),
513 || "local item should be in ast map".to_string());
516 ast_map::NodeVariant(v) => match v.node.kind {
517 ast::TupleVariantKind(ref args) => args.len() > 0,
520 ast_map::NodeStructCtor(_) => true,
527 // Create a monomorphic version of generic functions
528 if must_monomorphise {
529 // Should be either intra-crate or inlined.
530 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
532 let opt_ref_id = match node {
533 ExprId(id) => if id != 0 { Some(id) } else { None },
534 MethodCall(_) => None,
537 let (val, must_cast) =
538 monomorphize::monomorphic_fn(ccx, def_id, &substs, opt_ref_id);
540 if must_cast && node != ExprId(0) {
541 // Monotype of the REFERENCE to the function (type params
543 let ref_ty = match node {
544 ExprId(id) => node_id_type(bcx, id),
545 MethodCall(method_call) => {
546 let t = (*bcx.tcx().method_map.borrow())[method_call].ty;
547 monomorphize_type(bcx, t)
552 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
557 // Polytype of the function item (may have type params)
558 let fn_tpt = ty::lookup_item_type(tcx, def_id);
560 // Find the actual function pointer.
562 if def_id.krate == ast::LOCAL_CRATE {
563 // Internal reference.
564 get_item_val(ccx, def_id.node)
566 // External reference.
567 trans_external_path(ccx, def_id, fn_tpt.ty)
571 // This is subtle and surprising, but sometimes we have to bitcast
572 // the resulting fn pointer. The reason has to do with external
573 // functions. If you have two crates that both bind the same C
574 // library, they may not use precisely the same types: for
575 // example, they will probably each declare their own structs,
576 // which are distinct types from LLVM's point of view (nominal
579 // Now, if those two crates are linked into an application, and
580 // they contain inlined code, you can wind up with a situation
581 // where both of those functions wind up being loaded into this
582 // application simultaneously. In that case, the same function
583 // (from LLVM's point of view) requires two types. But of course
584 // LLVM won't allow one function to have two types.
586 // What we currently do, therefore, is declare the function with
587 // one of the two types (whichever happens to come first) and then
588 // bitcast as needed when the function is referenced to make sure
589 // it has the type we expect.
591 // This can occur on either a crate-local or crate-external
592 // reference. It also occurs when testing libcore and in some
593 // other weird situations. Annoying.
594 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
595 let llptrty = llty.ptr_to();
596 if val_ty(val) != llptrty {
597 debug!("trans_fn_ref_with_vtables(): casting pointer!");
598 val = BitCast(bcx, val, llptrty);
600 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
606 // ______________________________________________________________________
609 pub fn trans_call<'blk, 'tcx>(in_cx: Block<'blk, 'tcx>,
614 -> Block<'blk, 'tcx> {
615 let _icx = push_ctxt("trans_call");
616 trans_call_inner(in_cx,
617 Some(common::expr_info(call_ex)),
619 |cx, _| trans(cx, f),
624 pub fn trans_method_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
629 -> Block<'blk, 'tcx> {
630 let _icx = push_ctxt("trans_method_call");
631 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
632 let method_call = MethodCall::expr(call_ex.id);
633 let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
636 Some(common::expr_info(call_ex)),
637 monomorphize_type(bcx, method_ty),
638 |cx, arg_cleanup_scope| {
639 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
645 pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
648 dest: Option<expr::Dest>)
649 -> Result<'blk, 'tcx> {
650 let fty = if did.krate == ast::LOCAL_CRATE {
651 ty::node_id_to_type(bcx.tcx(), did.node)
653 csearch::get_type(bcx.tcx(), did).ty
655 callee::trans_call_inner(bcx,
659 trans_fn_ref_with_substs_to_callee(bcx,
662 subst::Substs::empty())
668 pub fn trans_call_inner<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
669 call_info: Option<NodeInfo>,
671 get_callee: |bcx: Block<'blk, 'tcx>,
672 arg_cleanup_scope: cleanup::ScopeId|
673 -> Callee<'blk, 'tcx>,
675 dest: Option<expr::Dest>)
676 -> Result<'blk, 'tcx> {
678 * This behemoth of a function translates function calls.
679 * Unfortunately, in order to generate more efficient LLVM
680 * output at -O0, it has quite a complex signature (refactoring
681 * this into two functions seems like a good idea).
683 * In particular, for lang items, it is invoked with a dest of
684 * None, and in that case the return value contains the result of
685 * the fn. The lang item must not return a structural type or else
686 * all heck breaks loose.
688 * For non-lang items, `dest` is always Some, and hence the result
689 * is written into memory somewhere. Nonetheless we return the
690 * actual return value of the function.
693 // Introduce a temporary cleanup scope that will contain cleanups
694 // for the arguments while they are being evaluated. The purpose
695 // this cleanup is to ensure that, should a panic occur while
696 // evaluating argument N, the values for arguments 0...N-1 are all
697 // cleaned up. If no panic occurs, the values are handed off to
698 // the callee, and hence none of the cleanups in this temporary
699 // scope will ever execute.
702 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
704 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
705 let mut bcx = callee.bcx;
707 let (abi, ret_ty) = match ty::get(callee_ty).sty {
708 ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
709 ty::ty_closure(ref f) => (f.abi, f.sig.output),
710 _ => panic!("expected bare rust fn or closure in trans_call_inner")
713 let (llfn, llenv, llself) = match callee.data {
718 (d.llfn, None, Some(d.llself))
721 // Closures are represented as (llfn, llclosure) pair:
722 // load the requisite values out.
723 let pair = d.to_llref();
724 let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
725 let llfn = Load(bcx, llfn);
726 let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
727 let llenv = Load(bcx, llenv);
728 (llfn, Some(llenv), None)
730 Intrinsic(node, substs) => {
731 assert!(abi == synabi::RustIntrinsic);
732 assert!(dest.is_some());
734 let call_info = call_info.expect("no call info for intrinsic call?");
735 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
736 arg_cleanup_scope, args,
737 dest.unwrap(), substs,
740 NamedTupleConstructor(substs, disr) => {
741 assert!(dest.is_some());
742 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
744 let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
745 return base::trans_named_tuple_constructor(bcx,
754 // Intrinsics should not become actual functions.
755 // We trans them in place in `trans_intrinsic_call`
756 assert!(abi != synabi::RustIntrinsic);
758 let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
760 // Generate a location to store the result. If the user does
761 // not care about the result, just make a stack slot.
762 let opt_llretslot = dest.and_then(|dest| match dest {
763 expr::SaveIn(dst) => Some(dst),
765 let ret_ty = match ret_ty {
766 ty::FnConverging(ret_ty) => ret_ty,
767 ty::FnDiverging => ty::mk_nil()
770 type_of::return_uses_outptr(ccx, ret_ty) ||
771 ty::type_needs_drop(bcx.tcx(), ret_ty) {
772 // Push the out-pointer if we use an out-pointer for this
773 // return type, otherwise push "undef".
774 if type_is_zero_size(ccx, ret_ty) {
775 let llty = type_of::type_of(ccx, ret_ty);
776 Some(C_undef(llty.ptr_to()))
778 Some(alloc_ty(bcx, ret_ty, "__llret"))
786 let mut llresult = unsafe {
787 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
790 // The code below invokes the function, using either the Rust
791 // conventions (if it is a rust fn) or the native conventions
792 // (otherwise). The important part is that, when all is said
793 // and done, either the return value of the function will have been
794 // written in opt_llretslot (if it is Some) or `llresult` will be
795 // set appropriately (otherwise).
797 let mut llargs = Vec::new();
799 if let (ty::FnConverging(ret_ty), Some(llretslot)) = (ret_ty, opt_llretslot) {
800 if type_of::return_uses_outptr(ccx, ret_ty) {
801 llargs.push(llretslot);
805 // Push the environment (or a trait object's self).
806 match (llenv, llself) {
807 (Some(llenv), None) => llargs.push(llenv),
808 (None, Some(llself)) => llargs.push(llself),
812 // Push the arguments.
813 bcx = trans_args(bcx,
817 cleanup::CustomScope(arg_cleanup_scope),
821 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
823 // Invoke the actual rust fn and update bcx/llresult.
824 let (llret, b) = base::invoke(bcx,
833 // If the Rust convention for this type is return via
834 // the return value, copy it into llretslot.
835 match (opt_llretslot, ret_ty) {
836 (Some(llretslot), ty::FnConverging(ret_ty)) => {
837 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
838 !type_is_zero_size(bcx.ccx(), ret_ty)
840 store_ty(bcx, llret, llretslot, ret_ty)
846 // Lang items are the only case where dest is None, and
847 // they are always Rust fns.
848 assert!(dest.is_some());
850 let mut llargs = Vec::new();
851 let arg_tys = match args {
852 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
853 _ => panic!("expected arg exprs.")
855 bcx = trans_args(bcx,
859 cleanup::CustomScope(arg_cleanup_scope),
862 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
864 bcx = foreign::trans_native_call(bcx, callee_ty,
865 llfn, opt_llretslot.unwrap(),
866 llargs.as_slice(), arg_tys);
869 fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_cleanup_scope);
871 // If the caller doesn't care about the result of this fn call,
872 // drop the temporary slot we made.
873 match (dest, opt_llretslot, ret_ty) {
874 (Some(expr::Ignore), Some(llretslot), ty::FnConverging(ret_ty)) => {
875 // drop the value if it is not being saved.
876 bcx = glue::drop_ty(bcx, llretslot, ret_ty, call_info);
877 call_lifetime_end(bcx, llretslot);
882 if ret_ty == ty::FnDiverging {
886 Result::new(bcx, llresult)
889 pub enum CallArgs<'a> {
890 // Supply value of arguments as a list of expressions that must be
891 // translated. This is used in the common case of `foo(bar, qux)`.
892 ArgExprs(&'a [P<ast::Expr>]),
894 // Supply value of arguments as a list of LLVM value refs; frequently
895 // used with lang items and so forth, when the argument is an internal
897 ArgVals(&'a [ValueRef]),
899 // For overloaded operators: `(lhs, Vec(rhs, rhs_id))`. `lhs`
900 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
901 // the right-hand-side arguments (if any).
902 ArgOverloadedOp(Datum<Expr>, Vec<(Datum<Expr>, ast::NodeId)>),
904 // Supply value of arguments as a list of expressions that must be
905 // translated, for overloaded call operators.
906 ArgOverloadedCall(Vec<&'a ast::Expr>),
909 fn trans_args_under_call_abi<'blk, 'tcx>(
910 mut bcx: Block<'blk, 'tcx>,
911 arg_exprs: &[P<ast::Expr>],
913 llargs: &mut Vec<ValueRef>,
914 arg_cleanup_scope: cleanup::ScopeId,
916 -> Block<'blk, 'tcx> {
917 // Translate the `self` argument first.
918 let arg_tys = ty::ty_fn_args(fn_ty);
920 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
921 llargs.push(unpack_result!(bcx, {
930 // Now untuple the rest of the arguments.
931 let tuple_expr = &arg_exprs[1];
932 let tuple_type = node_id_type(bcx, tuple_expr.id);
934 match ty::get(tuple_type).sty {
935 ty::ty_tup(ref field_types) => {
936 let tuple_datum = unpack_datum!(bcx,
937 expr::trans(bcx, &**tuple_expr));
938 let tuple_lvalue_datum =
940 tuple_datum.to_lvalue_datum(bcx,
943 let repr = adt::represent_type(bcx.ccx(), tuple_type);
944 let repr_ptr = &*repr;
945 for i in range(0, field_types.len()) {
946 let arg_datum = tuple_lvalue_datum.get_element(
950 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
952 let arg_datum = arg_datum.to_expr_datum();
954 unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
956 unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
957 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
962 bcx.sess().span_bug(tuple_expr.span,
963 "argument to `.call()` wasn't a tuple?!")
970 fn trans_overloaded_call_args<'blk, 'tcx>(
971 mut bcx: Block<'blk, 'tcx>,
972 arg_exprs: Vec<&ast::Expr>,
974 llargs: &mut Vec<ValueRef>,
975 arg_cleanup_scope: cleanup::ScopeId,
977 -> Block<'blk, 'tcx> {
978 // Translate the `self` argument first.
979 let arg_tys = ty::ty_fn_args(fn_ty);
981 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
982 llargs.push(unpack_result!(bcx, {
991 // Now untuple the rest of the arguments.
992 let tuple_type = arg_tys[1];
993 match ty::get(tuple_type).sty {
994 ty::ty_tup(ref field_types) => {
995 for (i, &field_type) in field_types.iter().enumerate() {
997 unpack_datum!(bcx, expr::trans(bcx, arg_exprs[i + 1]));
998 llargs.push(unpack_result!(bcx, {
1009 bcx.sess().span_bug(arg_exprs[0].span,
1010 "argument to `.call()` wasn't a tuple?!")
1017 pub fn trans_args<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
1020 llargs: &mut Vec<ValueRef> ,
1021 arg_cleanup_scope: cleanup::ScopeId,
1024 -> Block<'blk, 'tcx> {
1025 debug!("trans_args(abi={})", abi);
1027 let _icx = push_ctxt("trans_args");
1028 let arg_tys = ty::ty_fn_args(fn_ty);
1029 let variadic = ty::fn_is_variadic(fn_ty);
1033 // First we figure out the caller's view of the types of the arguments.
1034 // This will be needed if this is a generic call, because the callee has
1035 // to cast her view of the arguments to the caller's view.
1037 ArgExprs(arg_exprs) => {
1038 if abi == synabi::RustCall {
1039 // This is only used for direct calls to the `call`,
1040 // `call_mut` or `call_once` functions.
1041 return trans_args_under_call_abi(cx,
1049 let num_formal_args = arg_tys.len();
1050 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1051 if i == 0 && ignore_self {
1054 let arg_ty = if i >= num_formal_args {
1056 expr_ty_adjusted(cx, &**arg_expr)
1061 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1062 llargs.push(unpack_result!(bcx, {
1063 trans_arg_datum(bcx, arg_ty, arg_datum,
1069 ArgOverloadedCall(arg_exprs) => {
1070 return trans_overloaded_call_args(cx,
1077 ArgOverloadedOp(lhs, rhs) => {
1080 llargs.push(unpack_result!(bcx, {
1081 trans_arg_datum(bcx, arg_tys[0], lhs,
1086 assert_eq!(arg_tys.len(), 1 + rhs.len());
1087 for (rhs, rhs_id) in rhs.into_iter() {
1088 llargs.push(unpack_result!(bcx, {
1089 trans_arg_datum(bcx, arg_tys[1], rhs,
1091 DoAutorefArg(rhs_id))
1096 llargs.push_all(vs);
1103 pub enum AutorefArg {
1105 DoAutorefArg(ast::NodeId)
1108 pub fn trans_arg_datum<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1109 formal_arg_ty: ty::t,
1110 arg_datum: Datum<Expr>,
1111 arg_cleanup_scope: cleanup::ScopeId,
1112 autoref_arg: AutorefArg)
1113 -> Result<'blk, 'tcx> {
1114 let _icx = push_ctxt("trans_arg_datum");
1116 let ccx = bcx.ccx();
1118 debug!("trans_arg_datum({})",
1119 formal_arg_ty.repr(bcx.tcx()));
1121 let arg_datum_ty = arg_datum.ty;
1123 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1126 // FIXME(#3548) use the adjustments table
1128 DoAutorefArg(arg_id) => {
1129 // We will pass argument by reference
1130 // We want an lvalue, so that we can pass by reference and
1131 let arg_datum = unpack_datum!(
1132 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1133 val = arg_datum.val;
1136 // Make this an rvalue, since we are going to be
1137 // passing ownership.
1138 let arg_datum = unpack_datum!(
1139 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1141 // Now that arg_datum is owned, get it into the appropriate
1142 // mode (ref vs value).
1143 let arg_datum = unpack_datum!(
1144 bcx, arg_datum.to_appropriate_datum(bcx));
1146 // Technically, ownership of val passes to the callee.
1147 // However, we must cleanup should we panic before the
1148 // callee is actually invoked.
1149 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1153 if formal_arg_ty != arg_datum_ty {
1154 // this could happen due to e.g. subtyping
1155 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1156 debug!("casting actual type ({}) to match formal ({})",
1157 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1158 debug!("Rust types: {}; {}", ty_to_string(bcx.tcx(), arg_datum_ty),
1159 ty_to_string(bcx.tcx(), formal_arg_ty));
1160 val = PointerCast(bcx, val, llformal_arg_ty);
1163 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1164 Result::new(bcx, val)