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::ty::MethodCall;
53 use util::ppaux::Repr;
54 use util::ppaux::ty_to_string;
56 use syntax::abi as synabi;
61 pub struct MethodData {
66 pub enum CalleeData<'tcx> {
67 Closure(Datum<'tcx, Lvalue>),
69 // Constructor for enum variant/tuple-like-struct
71 NamedTupleConstructor(subst::Substs<'tcx>, ty::Disr),
73 // Represents a (possibly monomorphized) top-level fn item or method
74 // item. Note that this is just the fn-ptr and is not a Rust closure
75 // value (which is a pair).
76 Fn(/* llfn */ ValueRef),
78 Intrinsic(ast::NodeId, subst::Substs<'tcx>),
83 pub struct Callee<'blk, 'tcx: 'blk> {
84 pub bcx: Block<'blk, 'tcx>,
85 pub data: CalleeData<'tcx>,
88 fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
89 -> Callee<'blk, 'tcx> {
90 let _icx = push_ctxt("trans_callee");
91 debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
93 // pick out special kinds of expressions that can be called:
94 if let ast::ExprPath(_) = expr.node {
95 return trans_def(bcx, bcx.def(expr.id), expr);
98 // any other expressions are closures:
99 return datum_callee(bcx, expr);
101 fn datum_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
102 -> Callee<'blk, 'tcx> {
103 let DatumBlock {mut bcx, datum} = expr::trans(bcx, expr);
105 ty::ty_bare_fn(..) => {
106 let llval = datum.to_llscalarish(bcx);
112 ty::ty_closure(..) => {
113 let datum = unpack_datum!(
114 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
117 data: Closure(datum),
121 bcx.tcx().sess.span_bug(
123 format!("type of callee is neither bare-fn nor closure: \
125 bcx.ty_to_string(datum.ty)).as_slice());
130 fn fn_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, llfn: ValueRef)
131 -> Callee<'blk, 'tcx> {
138 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
140 ref_expr: &ast::Expr)
141 -> Callee<'blk, 'tcx> {
142 debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
143 let expr_ty = node_id_type(bcx, ref_expr.id);
145 def::DefFn(did, _) if {
146 let maybe_def_id = inline::get_local_instance(bcx.ccx(), did);
147 let maybe_ast_node = maybe_def_id.and_then(|def_id| bcx.tcx().map
149 match maybe_ast_node {
150 Some(ast_map::NodeStructCtor(_)) => true,
154 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
157 data: NamedTupleConstructor(substs, 0)
160 def::DefFn(did, _) if match expr_ty.sty {
161 ty::ty_bare_fn(ref f) => f.abi == synabi::RustIntrinsic,
164 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
165 let def_id = inline::maybe_instantiate_inline(bcx.ccx(), did);
166 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
168 def::DefFn(did, _) | def::DefMethod(did, _, def::FromImpl(_)) |
169 def::DefStaticMethod(did, def::FromImpl(_)) => {
170 fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
172 def::DefStaticMethod(meth_did, def::FromTrait(trait_did)) |
173 def::DefMethod(meth_did, _, def::FromTrait(trait_did)) => {
174 fn_callee(bcx, meth::trans_static_method_callee(bcx, meth_did,
178 def::DefVariant(tid, vid, _) => {
179 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
180 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
182 // Nullary variants are not callable
183 assert!(vinfo.args.len() > 0u);
187 data: NamedTupleConstructor(substs, vinfo.disr_val)
190 def::DefStruct(_) => {
191 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
194 data: NamedTupleConstructor(substs, 0)
200 def::DefUpvar(..) => {
201 datum_callee(bcx, ref_expr)
203 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
204 def::DefTy(..) | def::DefPrimTy(..) | def::DefAssociatedTy(..) |
205 def::DefUse(..) | def::DefTyParamBinder(..) |
206 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
207 def::DefSelfTy(..) => {
208 bcx.tcx().sess.span_bug(
210 format!("cannot translate def {} \
211 to a callable thing!", def).as_slice());
217 /// Translates a reference (with id `ref_id`) to the fn/method with id `def_id` into a function
218 /// pointer. This may require monomorphization or inlining.
219 pub fn trans_fn_ref(bcx: Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
220 let _icx = push_ctxt("trans_fn_ref");
222 let substs = node_id_substs(bcx, node);
223 debug!("trans_fn_ref(def_id={}, node={}, substs={})",
224 def_id.repr(bcx.tcx()),
226 substs.repr(bcx.tcx()));
227 trans_fn_ref_with_substs(bcx, def_id, node, substs)
230 fn trans_fn_ref_with_substs_to_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
233 substs: subst::Substs<'tcx>)
234 -> Callee<'blk, 'tcx> {
237 data: Fn(trans_fn_ref_with_substs(bcx,
244 /// Translates an adapter that implements the `Fn` trait for a fn
245 /// pointer. This is basically the equivalent of something like:
248 /// impl<'a> Fn(&'a int) -> &'a int for fn(&int) -> &int {
249 /// extern "rust-abi" fn call(&self, args: (&'a int,)) -> &'a int {
255 /// but for the bare function type given.
256 pub fn trans_fn_pointer_shim<'a, 'tcx>(
257 ccx: &'a CrateContext<'a, 'tcx>,
258 bare_fn_ty: Ty<'tcx>)
261 let _icx = push_ctxt("trans_fn_pointer_shim");
264 let bare_fn_ty = ty::normalize_ty(tcx, bare_fn_ty);
265 match ccx.fn_pointer_shims().borrow().get(&bare_fn_ty) {
266 Some(&llval) => { return llval; }
270 debug!("trans_fn_pointer_shim(bare_fn_ty={})",
271 bare_fn_ty.repr(tcx));
273 // This is an impl of `Fn` trait, so receiver is `&self`.
274 let bare_fn_ty_ref = ty::mk_imm_rptr(tcx, ty::ReStatic, bare_fn_ty);
276 // Construct the "tuply" version of `bare_fn_ty`. It takes two arguments: `self`,
277 // which is the fn pointer, and `args`, which is the arguments tuple.
278 let (input_tys, output_ty) =
279 match bare_fn_ty.sty {
280 ty::ty_bare_fn(ty::BareFnTy { fn_style: ast::NormalFn,
282 sig: ty::FnSig { inputs: ref input_tys,
284 variadic: false }}) =>
286 (input_tys, output_ty)
290 tcx.sess.bug(format!("trans_fn_pointer_shim invoked on invalid type: {}",
291 bare_fn_ty.repr(tcx)).as_slice());
294 let tuple_input_ty = ty::mk_tup(tcx, input_tys.to_vec());
295 let tuple_fn_ty = ty::mk_bare_fn(tcx,
296 ty::BareFnTy { fn_style: ast::NormalFn,
297 abi: synabi::RustCall,
299 inputs: vec![bare_fn_ty_ref,
304 debug!("tuple_fn_ty: {}", tuple_fn_ty.repr(tcx));
308 link::mangle_internal_name_by_type_and_seq(ccx, bare_fn_ty,
311 decl_internal_rust_fn(ccx,
313 function_name.as_slice());
316 let block_arena = TypedArena::new();
317 let empty_substs = Substs::trans_empty();
318 let fcx = new_fn_ctxt(ccx,
326 let mut bcx = init_function(&fcx, false, output_ty);
328 // the first argument (`self`) will be ptr to the the fn pointer
330 Load(bcx, get_param(fcx.llfn, fcx.arg_pos(0) as u32));
332 // the remaining arguments will be the untupled values
336 .map(|(i, _)| get_param(fcx.llfn, fcx.arg_pos(i+1) as u32))
338 assert!(!fcx.needs_ret_allocas);
340 let dest = fcx.llretslotptr.get().map(|_|
341 expr::SaveIn(fcx.get_ret_slot(bcx, output_ty, "ret_slot"))
344 bcx = trans_call_inner(bcx,
347 |bcx, _| Callee { bcx: bcx, data: Fn(llfnpointer) },
348 ArgVals(llargs.as_slice()),
351 finish_fn(&fcx, bcx, output_ty);
353 ccx.fn_pointer_shims().borrow_mut().insert(bare_fn_ty, llfn);
358 /// Translates the adapter that deconstructs a `Box<Trait>` object into
359 /// `Trait` so that a by-value self method can be called.
360 pub fn trans_unboxing_shim<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
361 llshimmedfn: ValueRef,
362 fty: &ty::BareFnTy<'tcx>,
363 method_id: ast::DefId,
364 substs: &subst::Substs<'tcx>)
366 let _icx = push_ctxt("trans_unboxing_shim");
370 let fty = fty.subst(tcx, substs);
372 // Transform the self type to `Box<self_type>`.
373 let self_type = fty.sig.inputs[0];
374 let boxed_self_type = ty::mk_uniq(tcx, self_type);
375 let boxed_function_type = ty::FnSig {
376 inputs: fty.sig.inputs.iter().enumerate().map(|(i, typ)| {
383 output: fty.sig.output,
386 let boxed_function_type = ty::BareFnTy {
387 fn_style: fty.fn_style,
389 sig: boxed_function_type,
391 let boxed_function_type = ty::mk_bare_fn(tcx, boxed_function_type);
392 let function_type = match fty.abi {
393 synabi::RustCall => {
394 // We're passing through to a RustCall ABI function, but
395 // because the shim will already perform untupling, we
396 // need to pretend the shimmed function does not use
397 // RustCall so the untupled arguments can be passed
398 // through verbatim. This is kind of ugly.
399 let fake_ty = ty::FnSig {
400 inputs: type_of::untuple_arguments_if_necessary(ccx,
401 fty.sig.inputs.as_slice(),
403 output: fty.sig.output,
406 let fake_ty = ty::BareFnTy {
407 fn_style: fty.fn_style,
411 ty::mk_bare_fn(tcx, fake_ty)
414 ty::mk_bare_fn(tcx, fty)
418 let function_name = ty::with_path(tcx, method_id, |path| {
419 link::mangle_internal_name_by_path_and_seq(path, "unboxing_shim")
421 let llfn = decl_internal_rust_fn(ccx,
423 function_name.as_slice());
425 let block_arena = TypedArena::new();
426 let empty_param_substs = Substs::trans_empty();
427 let return_type = ty::ty_fn_ret(boxed_function_type);
428 let fcx = new_fn_ctxt(ccx,
436 let mut bcx = init_function(&fcx, false, return_type);
438 // Create the substituted versions of the self type.
439 let arg_scope = fcx.push_custom_cleanup_scope();
440 let arg_scope_id = cleanup::CustomScope(arg_scope);
441 let boxed_self_type = ty::ty_fn_args(boxed_function_type)[0];
442 let arg_types = ty::ty_fn_args(function_type);
443 let self_type = arg_types[0];
444 let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
446 // Create a datum for self.
447 let llboxedself = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
448 let llboxedself = Datum::new(llboxedself,
453 llboxedself.to_lvalue_datum_in_scope(bcx,
457 // This `Load` is needed because lvalue data are always by-ref.
458 let llboxedself = Load(bcx, boxed_self.val);
460 let llself = if type_is_immediate(ccx, self_type) {
461 let llboxedself = Load(bcx, llboxedself);
462 immediate_rvalue(llboxedself, self_type)
464 let llself = rvalue_scratch_datum(bcx, self_type, "self");
465 memcpy_ty(bcx, llself.val, llboxedself, self_type);
469 // Make sure we don't free the box twice!
470 boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type);
472 // Schedule a cleanup to free the box.
473 fcx.schedule_free_value(arg_scope_id,
475 cleanup::HeapExchange,
478 // Now call the function.
479 let mut llshimmedargs = vec!(llself.val);
480 for i in range(1, arg_types.len()) {
481 llshimmedargs.push(get_param(fcx.llfn, fcx.arg_pos(i) as u32));
483 assert!(!fcx.needs_ret_allocas);
484 let dest = fcx.llretslotptr.get().map(|_|
485 expr::SaveIn(fcx.get_ret_slot(bcx, return_type, "ret_slot"))
487 bcx = trans_call_inner(bcx,
493 data: Fn(llshimmedfn),
496 ArgVals(llshimmedargs.as_slice()),
499 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
500 finish_fn(&fcx, bcx, return_type);
505 /// Translates a reference to a fn/method item, monomorphizing and
506 /// inlining as it goes.
510 /// - `bcx`: the current block where the reference to the fn occurs
511 /// - `def_id`: def id of the fn or method item being referenced
512 /// - `node`: node id of the reference to the fn/method, if applicable.
513 /// This parameter may be zero; but, if so, the resulting value may not
514 /// have the right type, so it must be cast before being used.
515 /// - `substs`: values for each of the fn/method's parameters
516 pub fn trans_fn_ref_with_substs<'blk, 'tcx>(
517 bcx: Block<'blk, 'tcx>, //
518 def_id: ast::DefId, // def id of fn
519 node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
520 substs: subst::Substs<'tcx>) // vtables for the call
523 let _icx = push_ctxt("trans_fn_ref_with_substs");
527 debug!("trans_fn_ref_with_substs(bcx={}, def_id={}, node={}, \
534 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
535 assert!(substs.types.all(|t| !ty::type_has_escaping_regions(*t)));
536 let substs = substs.erase_regions();
538 // Load the info for the appropriate trait if necessary.
539 match ty::trait_of_item(tcx, def_id) {
542 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
546 // We need to do a bunch of special handling for default methods.
547 // We need to modify the def_id and our substs in order to monomorphize
549 let (is_default, def_id, substs) = match ty::provided_source(tcx, def_id) {
550 None => (false, def_id, substs),
552 // There are two relevant substitutions when compiling
553 // default methods. First, there is the substitution for
554 // the type parameters of the impl we are using and the
555 // method we are calling. This substitution is the substs
556 // argument we already have.
557 // In order to compile a default method, though, we need
558 // to consider another substitution: the substitution for
559 // the type parameters on trait; the impl we are using
560 // implements the trait at some particular type
561 // parameters, and we need to substitute for those first.
562 // So, what we need to do is find this substitution and
563 // compose it with the one we already have.
565 let impl_id = ty::impl_or_trait_item(tcx, def_id).container()
567 let impl_or_trait_item = ty::impl_or_trait_item(tcx, source_id);
568 match impl_or_trait_item {
569 ty::MethodTraitItem(method) => {
570 let trait_ref = ty::impl_trait_ref(tcx, impl_id).unwrap();
571 let trait_ref = ty::erase_late_bound_regions(tcx, &trait_ref);
573 // Compute the first substitution
575 ty::make_substs_for_receiver_types(tcx, &*trait_ref, &*method)
579 let new_substs = first_subst.subst(tcx, &substs);
581 debug!("trans_fn_with_vtables - default method: \
582 substs = {}, trait_subst = {}, \
583 first_subst = {}, new_subst = {}",
584 substs.repr(tcx), trait_ref.substs.repr(tcx),
585 first_subst.repr(tcx), new_substs.repr(tcx));
587 (true, source_id, new_substs)
589 ty::TypeTraitItem(_) => {
590 bcx.tcx().sess.bug("trans_fn_ref_with_vtables() tried \
591 to translate an associated type?!")
597 // If this is an unboxed closure, redirect to it.
598 match closure::get_or_create_declaration_if_unboxed_closure(bcx,
602 Some(llfn) => return llfn,
605 // Check whether this fn has an inlined copy and, if so, redirect
606 // def_id to the local id of the inlined copy.
607 let def_id = inline::maybe_instantiate_inline(ccx, def_id);
609 // We must monomorphise if the fn has type parameters, is a default method,
610 // or is a named tuple constructor.
611 let must_monomorphise = if !substs.types.is_empty() || is_default {
613 } else if def_id.krate == ast::LOCAL_CRATE {
614 let map_node = session::expect(
616 tcx.map.find(def_id.node),
617 || "local item should be in ast map".to_string());
620 ast_map::NodeVariant(v) => match v.node.kind {
621 ast::TupleVariantKind(ref args) => args.len() > 0,
624 ast_map::NodeStructCtor(_) => true,
631 // Create a monomorphic version of generic functions
632 if must_monomorphise {
633 // Should be either intra-crate or inlined.
634 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
636 let opt_ref_id = match node {
637 ExprId(id) => if id != 0 { Some(id) } else { None },
638 MethodCall(_) => None,
641 let (val, must_cast) =
642 monomorphize::monomorphic_fn(ccx, def_id, &substs, opt_ref_id);
644 if must_cast && node != ExprId(0) {
645 // Monotype of the REFERENCE to the function (type params
647 let ref_ty = match node {
648 ExprId(id) => node_id_type(bcx, id),
649 MethodCall(method_call) => {
650 let t = (*bcx.tcx().method_map.borrow())[method_call].ty;
651 monomorphize_type(bcx, t)
656 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
661 // Polytype of the function item (may have type params)
662 let fn_tpt = ty::lookup_item_type(tcx, def_id);
664 // Find the actual function pointer.
666 if def_id.krate == ast::LOCAL_CRATE {
667 // Internal reference.
668 get_item_val(ccx, def_id.node)
670 // External reference.
671 trans_external_path(ccx, def_id, fn_tpt.ty)
675 // This is subtle and surprising, but sometimes we have to bitcast
676 // the resulting fn pointer. The reason has to do with external
677 // functions. If you have two crates that both bind the same C
678 // library, they may not use precisely the same types: for
679 // example, they will probably each declare their own structs,
680 // which are distinct types from LLVM's point of view (nominal
683 // Now, if those two crates are linked into an application, and
684 // they contain inlined code, you can wind up with a situation
685 // where both of those functions wind up being loaded into this
686 // application simultaneously. In that case, the same function
687 // (from LLVM's point of view) requires two types. But of course
688 // LLVM won't allow one function to have two types.
690 // What we currently do, therefore, is declare the function with
691 // one of the two types (whichever happens to come first) and then
692 // bitcast as needed when the function is referenced to make sure
693 // it has the type we expect.
695 // This can occur on either a crate-local or crate-external
696 // reference. It also occurs when testing libcore and in some
697 // other weird situations. Annoying.
698 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
699 let llptrty = llty.ptr_to();
700 if val_ty(val) != llptrty {
701 debug!("trans_fn_ref_with_vtables(): casting pointer!");
702 val = BitCast(bcx, val, llptrty);
704 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
710 // ______________________________________________________________________
713 pub fn trans_call<'a, 'blk, 'tcx>(in_cx: Block<'blk, 'tcx>,
716 args: CallArgs<'a, 'tcx>,
718 -> Block<'blk, 'tcx> {
719 let _icx = push_ctxt("trans_call");
720 trans_call_inner(in_cx,
721 Some(common::expr_info(call_ex)),
723 |cx, _| trans(cx, f),
728 pub fn trans_method_call<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
731 args: CallArgs<'a, 'tcx>,
733 -> Block<'blk, 'tcx> {
734 let _icx = push_ctxt("trans_method_call");
735 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
736 let method_call = MethodCall::expr(call_ex.id);
737 let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
740 Some(common::expr_info(call_ex)),
741 monomorphize_type(bcx, method_ty),
742 |cx, arg_cleanup_scope| {
743 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
749 pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
752 dest: Option<expr::Dest>)
753 -> Result<'blk, 'tcx> {
754 let fty = if did.krate == ast::LOCAL_CRATE {
755 ty::node_id_to_type(bcx.tcx(), did.node)
757 csearch::get_type(bcx.tcx(), did).ty
759 callee::trans_call_inner(bcx,
763 trans_fn_ref_with_substs_to_callee(bcx,
766 subst::Substs::trans_empty())
772 /// This behemoth of a function translates function calls. Unfortunately, in order to generate more
773 /// efficient LLVM output at -O0, it has quite a complex signature (refactoring this into two
774 /// functions seems like a good idea).
776 /// In particular, for lang items, it is invoked with a dest of None, and in that case the return
777 /// value contains the result of the fn. The lang item must not return a structural type or else
778 /// all heck breaks loose.
780 /// For non-lang items, `dest` is always Some, and hence the result is written into memory
781 /// somewhere. Nonetheless we return the actual return value of the function.
782 pub fn trans_call_inner<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
783 call_info: Option<NodeInfo>,
785 get_callee: |bcx: Block<'blk, 'tcx>,
786 arg_cleanup_scope: cleanup::ScopeId|
787 -> Callee<'blk, 'tcx>,
788 args: CallArgs<'a, 'tcx>,
789 dest: Option<expr::Dest>)
790 -> Result<'blk, 'tcx> {
791 // Introduce a temporary cleanup scope that will contain cleanups
792 // for the arguments while they are being evaluated. The purpose
793 // this cleanup is to ensure that, should a panic occur while
794 // evaluating argument N, the values for arguments 0...N-1 are all
795 // cleaned up. If no panic occurs, the values are handed off to
796 // the callee, and hence none of the cleanups in this temporary
797 // scope will ever execute.
800 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
802 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
803 let mut bcx = callee.bcx;
805 let (abi, ret_ty) = match callee_ty.sty {
806 ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
807 ty::ty_closure(ref f) => (f.abi, f.sig.output),
808 _ => panic!("expected bare rust fn or closure in trans_call_inner")
811 let (llfn, llenv, llself) = match callee.data {
816 (d.llfn, None, Some(d.llself))
819 // Closures are represented as (llfn, llclosure) pair:
820 // load the requisite values out.
821 let pair = d.to_llref();
822 let llfn = GEPi(bcx, pair, &[0u, abi::FAT_PTR_ADDR]);
823 let llfn = Load(bcx, llfn);
824 let llenv = GEPi(bcx, pair, &[0u, abi::FAT_PTR_EXTRA]);
825 let llenv = Load(bcx, llenv);
826 (llfn, Some(llenv), None)
828 Intrinsic(node, substs) => {
829 assert!(abi == synabi::RustIntrinsic);
830 assert!(dest.is_some());
832 let call_info = call_info.expect("no call info for intrinsic call?");
833 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
834 arg_cleanup_scope, args,
835 dest.unwrap(), substs,
838 NamedTupleConstructor(substs, disr) => {
839 assert!(dest.is_some());
840 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
842 let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
843 return base::trans_named_tuple_constructor(bcx,
852 // Intrinsics should not become actual functions.
853 // We trans them in place in `trans_intrinsic_call`
854 assert!(abi != synabi::RustIntrinsic);
856 let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
858 // Generate a location to store the result. If the user does
859 // not care about the result, just make a stack slot.
860 let opt_llretslot = dest.and_then(|dest| match dest {
861 expr::SaveIn(dst) => Some(dst),
863 let ret_ty = match ret_ty {
864 ty::FnConverging(ret_ty) => ret_ty,
865 ty::FnDiverging => ty::mk_nil(ccx.tcx())
868 type_of::return_uses_outptr(ccx, ret_ty) ||
869 ty::type_needs_drop(bcx.tcx(), ret_ty) {
870 // Push the out-pointer if we use an out-pointer for this
871 // return type, otherwise push "undef".
872 if type_is_zero_size(ccx, ret_ty) {
873 let llty = type_of::type_of(ccx, ret_ty);
874 Some(C_undef(llty.ptr_to()))
876 Some(alloc_ty(bcx, ret_ty, "__llret"))
884 let mut llresult = unsafe {
885 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
888 // The code below invokes the function, using either the Rust
889 // conventions (if it is a rust fn) or the native conventions
890 // (otherwise). The important part is that, when all is said
891 // and done, either the return value of the function will have been
892 // written in opt_llretslot (if it is Some) or `llresult` will be
893 // set appropriately (otherwise).
895 let mut llargs = Vec::new();
897 if let (ty::FnConverging(ret_ty), Some(llretslot)) = (ret_ty, opt_llretslot) {
898 if type_of::return_uses_outptr(ccx, ret_ty) {
899 llargs.push(llretslot);
903 // Push the environment (or a trait object's self).
904 match (llenv, llself) {
905 (Some(llenv), None) => llargs.push(llenv),
906 (None, Some(llself)) => llargs.push(llself),
910 // Push the arguments.
911 bcx = trans_args(bcx,
915 cleanup::CustomScope(arg_cleanup_scope),
919 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
921 // Invoke the actual rust fn and update bcx/llresult.
922 let (llret, b) = base::invoke(bcx,
931 // If the Rust convention for this type is return via
932 // the return value, copy it into llretslot.
933 match (opt_llretslot, ret_ty) {
934 (Some(llretslot), ty::FnConverging(ret_ty)) => {
935 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
936 !type_is_zero_size(bcx.ccx(), ret_ty)
938 store_ty(bcx, llret, llretslot, ret_ty)
944 // Lang items are the only case where dest is None, and
945 // they are always Rust fns.
946 assert!(dest.is_some());
948 let mut llargs = Vec::new();
949 let arg_tys = match args {
950 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
951 _ => panic!("expected arg exprs.")
953 bcx = trans_args(bcx,
957 cleanup::CustomScope(arg_cleanup_scope),
960 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
962 bcx = foreign::trans_native_call(bcx, callee_ty,
963 llfn, opt_llretslot.unwrap(),
964 llargs.as_slice(), arg_tys);
967 fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_cleanup_scope);
969 // If the caller doesn't care about the result of this fn call,
970 // drop the temporary slot we made.
971 match (dest, opt_llretslot, ret_ty) {
972 (Some(expr::Ignore), Some(llretslot), ty::FnConverging(ret_ty)) => {
973 // drop the value if it is not being saved.
974 bcx = glue::drop_ty(bcx, llretslot, ret_ty, call_info);
975 call_lifetime_end(bcx, llretslot);
980 if ret_ty == ty::FnDiverging {
984 Result::new(bcx, llresult)
987 pub enum CallArgs<'a, 'tcx> {
988 // Supply value of arguments as a list of expressions that must be
989 // translated. This is used in the common case of `foo(bar, qux)`.
990 ArgExprs(&'a [P<ast::Expr>]),
992 // Supply value of arguments as a list of LLVM value refs; frequently
993 // used with lang items and so forth, when the argument is an internal
995 ArgVals(&'a [ValueRef]),
997 // For overloaded operators: `(lhs, Vec(rhs, rhs_id))`. `lhs`
998 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
999 // the right-hand-side arguments (if any).
1000 ArgOverloadedOp(Datum<'tcx, Expr>, Vec<(Datum<'tcx, Expr>, ast::NodeId)>),
1002 // Supply value of arguments as a list of expressions that must be
1003 // translated, for overloaded call operators.
1004 ArgOverloadedCall(Vec<&'a ast::Expr>),
1007 fn trans_args_under_call_abi<'blk, 'tcx>(
1008 mut bcx: Block<'blk, 'tcx>,
1009 arg_exprs: &[P<ast::Expr>],
1011 llargs: &mut Vec<ValueRef>,
1012 arg_cleanup_scope: cleanup::ScopeId,
1014 -> Block<'blk, 'tcx> {
1015 // Translate the `self` argument first.
1017 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
1018 llargs.push(unpack_result!(bcx, {
1019 trans_arg_datum(bcx,
1020 ty::ty_fn_args(fn_ty)[0],
1027 // Now untuple the rest of the arguments.
1028 let tuple_expr = &arg_exprs[1];
1029 let tuple_type = node_id_type(bcx, tuple_expr.id);
1031 match tuple_type.sty {
1032 ty::ty_tup(ref field_types) => {
1033 let tuple_datum = unpack_datum!(bcx,
1034 expr::trans(bcx, &**tuple_expr));
1035 let tuple_lvalue_datum =
1037 tuple_datum.to_lvalue_datum(bcx,
1040 let repr = adt::represent_type(bcx.ccx(), tuple_type);
1041 let repr_ptr = &*repr;
1042 for i in range(0, field_types.len()) {
1043 let arg_datum = tuple_lvalue_datum.get_element(
1047 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
1049 let arg_datum = arg_datum.to_expr_datum();
1051 unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1053 unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
1054 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
1058 bcx.sess().span_bug(tuple_expr.span,
1059 "argument to `.call()` wasn't a tuple?!")
1066 fn trans_overloaded_call_args<'blk, 'tcx>(
1067 mut bcx: Block<'blk, 'tcx>,
1068 arg_exprs: Vec<&ast::Expr>,
1070 llargs: &mut Vec<ValueRef>,
1071 arg_cleanup_scope: cleanup::ScopeId,
1073 -> Block<'blk, 'tcx> {
1074 // Translate the `self` argument first.
1075 let arg_tys = ty::ty_fn_args(fn_ty);
1077 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
1078 llargs.push(unpack_result!(bcx, {
1079 trans_arg_datum(bcx,
1087 // Now untuple the rest of the arguments.
1088 let tuple_type = arg_tys[1];
1089 match tuple_type.sty {
1090 ty::ty_tup(ref field_types) => {
1091 for (i, &field_type) in field_types.iter().enumerate() {
1093 unpack_datum!(bcx, expr::trans(bcx, arg_exprs[i + 1]));
1094 llargs.push(unpack_result!(bcx, {
1095 trans_arg_datum(bcx,
1104 bcx.sess().span_bug(arg_exprs[0].span,
1105 "argument to `.call()` wasn't a tuple?!")
1112 pub fn trans_args<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
1113 args: CallArgs<'a, 'tcx>,
1115 llargs: &mut Vec<ValueRef>,
1116 arg_cleanup_scope: cleanup::ScopeId,
1119 -> Block<'blk, 'tcx> {
1120 debug!("trans_args(abi={})", abi);
1122 let _icx = push_ctxt("trans_args");
1123 let arg_tys = ty::ty_fn_args(fn_ty);
1124 let variadic = ty::fn_is_variadic(fn_ty);
1128 // First we figure out the caller's view of the types of the arguments.
1129 // This will be needed if this is a generic call, because the callee has
1130 // to cast her view of the arguments to the caller's view.
1132 ArgExprs(arg_exprs) => {
1133 if abi == synabi::RustCall {
1134 // This is only used for direct calls to the `call`,
1135 // `call_mut` or `call_once` functions.
1136 return trans_args_under_call_abi(cx,
1144 let num_formal_args = arg_tys.len();
1145 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1146 if i == 0 && ignore_self {
1149 let arg_ty = if i >= num_formal_args {
1151 expr_ty_adjusted(cx, &**arg_expr)
1156 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1157 llargs.push(unpack_result!(bcx, {
1158 trans_arg_datum(bcx, arg_ty, arg_datum,
1164 ArgOverloadedCall(arg_exprs) => {
1165 return trans_overloaded_call_args(cx,
1172 ArgOverloadedOp(lhs, rhs) => {
1175 llargs.push(unpack_result!(bcx, {
1176 trans_arg_datum(bcx, arg_tys[0], lhs,
1181 assert_eq!(arg_tys.len(), 1 + rhs.len());
1182 for (rhs, rhs_id) in rhs.into_iter() {
1183 llargs.push(unpack_result!(bcx, {
1184 trans_arg_datum(bcx, arg_tys[1], rhs,
1186 DoAutorefArg(rhs_id))
1191 llargs.push_all(vs);
1198 pub enum AutorefArg {
1200 DoAutorefArg(ast::NodeId)
1203 pub fn trans_arg_datum<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1204 formal_arg_ty: Ty<'tcx>,
1205 arg_datum: Datum<'tcx, Expr>,
1206 arg_cleanup_scope: cleanup::ScopeId,
1207 autoref_arg: AutorefArg)
1208 -> Result<'blk, 'tcx> {
1209 let _icx = push_ctxt("trans_arg_datum");
1211 let ccx = bcx.ccx();
1213 debug!("trans_arg_datum({})",
1214 formal_arg_ty.repr(bcx.tcx()));
1216 let arg_datum_ty = arg_datum.ty;
1218 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1221 // FIXME(#3548) use the adjustments table
1223 DoAutorefArg(arg_id) => {
1224 // We will pass argument by reference
1225 // We want an lvalue, so that we can pass by reference and
1226 let arg_datum = unpack_datum!(
1227 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1228 val = arg_datum.val;
1231 // Make this an rvalue, since we are going to be
1232 // passing ownership.
1233 let arg_datum = unpack_datum!(
1234 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1236 // Now that arg_datum is owned, get it into the appropriate
1237 // mode (ref vs value).
1238 let arg_datum = unpack_datum!(
1239 bcx, arg_datum.to_appropriate_datum(bcx));
1241 // Technically, ownership of val passes to the callee.
1242 // However, we must cleanup should we panic before the
1243 // callee is actually invoked.
1244 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1248 if formal_arg_ty != arg_datum_ty {
1249 // this could happen due to e.g. subtyping
1250 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1251 debug!("casting actual type ({}) to match formal ({})",
1252 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1253 debug!("Rust types: {}; {}", ty_to_string(bcx.tcx(), arg_datum_ty),
1254 ty_to_string(bcx.tcx(), formal_arg_ty));
1255 val = PointerCast(bcx, val, llformal_arg_ty);
1258 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1259 Result::new(bcx, val)