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, VecPerParamSpace};
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::datum::{Datum, KindOps};
41 use middle::trans::expr;
42 use middle::trans::glue;
43 use middle::trans::inline;
44 use middle::trans::foreign;
45 use middle::trans::intrinsic;
46 use middle::trans::meth;
47 use middle::trans::monomorphize;
48 use middle::trans::type_::Type;
49 use middle::trans::type_of;
52 use middle::typeck::coherence::make_substs_for_receiver_types;
53 use middle::typeck::MethodCall;
54 use util::ppaux::Repr;
59 use synabi = syntax::abi;
61 pub struct MethodData {
67 Closure(Datum<Lvalue>),
69 // Constructor for enum variant/tuple-like-struct
71 NamedTupleConstructor(subst::Substs, 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),
80 TraitMethod(MethodData)
83 pub struct Callee<'a> {
84 pub bcx: &'a Block<'a>,
88 fn trans<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
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<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
104 let DatumBlock {bcx: mut bcx, datum} = expr::trans(bcx, expr);
105 match ty::get(datum.ty).sty {
106 ty::ty_bare_fn(..) => {
107 let llval = datum.to_llscalarish(bcx);
113 ty::ty_closure(..) => {
114 let datum = unpack_datum!(
115 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
118 data: Closure(datum),
122 bcx.tcx().sess.span_bug(
124 format!("type of callee is neither bare-fn nor closure: \
126 bcx.ty_to_string(datum.ty)).as_slice());
131 fn fn_callee<'a>(bcx: &'a Block<'a>, llfn: ValueRef) -> Callee<'a> {
138 fn trans_def<'a>(bcx: &'a Block<'a>, def: def::Def, ref_expr: &ast::Expr)
140 debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
141 let expr_ty = node_id_type(bcx, ref_expr.id);
143 def::DefFn(did, _) if {
144 let def_id = if did.krate != ast::LOCAL_CRATE {
145 inline::maybe_instantiate_inline(bcx.ccx(), did)
149 match bcx.tcx().map.find(def_id.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 ty::get(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 = if did.krate != ast::LOCAL_CRATE {
166 inline::maybe_instantiate_inline(bcx.ccx(), did)
170 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
173 def::DefStaticMethod(did, def::FromImpl(_), _) => {
174 fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
176 def::DefStaticMethod(impl_did,
177 def::FromTrait(trait_did),
179 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
183 def::DefVariant(tid, vid, _) => {
184 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
185 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
187 // Nullary variants are not callable
188 assert!(vinfo.args.len() > 0u);
192 data: NamedTupleConstructor(substs, vinfo.disr_val)
195 def::DefStruct(_) => {
196 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
199 data: NamedTupleConstructor(substs, 0)
205 def::DefBinding(..) |
206 def::DefUpvar(..) => {
207 datum_callee(bcx, ref_expr)
209 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
210 def::DefTy(..) | def::DefPrimTy(..) |
211 def::DefUse(..) | def::DefTyParamBinder(..) |
212 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
213 def::DefSelfTy(..) | def::DefMethod(..) => {
214 bcx.tcx().sess.span_bug(
216 format!("cannot translate def {:?} \
217 to a callable thing!", def).as_slice());
223 pub fn trans_fn_ref(bcx: &Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
225 * Translates a reference (with id `ref_id`) to the fn/method
226 * with id `def_id` into a function pointer. This may require
227 * monomorphization or inlining.
230 let _icx = push_ctxt("trans_fn_ref");
232 let substs = node_id_substs(bcx, node);
233 let vtable_key = match node {
234 ExprId(id) => MethodCall::expr(id),
235 MethodCall(method_call) => method_call
237 let vtables = node_vtables(bcx, vtable_key);
238 debug!("trans_fn_ref(def_id={}, node={:?}, substs={}, vtables={})",
239 def_id.repr(bcx.tcx()),
241 substs.repr(bcx.tcx()),
242 vtables.repr(bcx.tcx()));
243 trans_fn_ref_with_vtables(bcx, def_id, node, substs, vtables)
246 fn trans_fn_ref_with_vtables_to_callee<'a>(bcx: &'a Block<'a>,
249 substs: subst::Substs,
250 vtables: typeck::vtable_res)
254 data: Fn(trans_fn_ref_with_vtables(bcx,
262 fn resolve_default_method_vtables(bcx: &Block,
264 substs: &subst::Substs,
265 impl_vtables: typeck::vtable_res)
266 -> typeck::vtable_res
268 // Get the vtables that the impl implements the trait at
269 let impl_res = ty::lookup_impl_vtables(bcx.tcx(), impl_id);
271 // Build up a param_substs that we are going to resolve the
272 // trait_vtables under.
273 let param_substs = param_substs {
274 substs: (*substs).clone(),
275 vtables: impl_vtables.clone()
278 let mut param_vtables = resolve_vtables_under_param_substs(
279 bcx.tcx(), ¶m_substs, &impl_res);
281 // Now we pull any vtables for parameters on the actual method.
282 param_vtables.push_all(subst::FnSpace,
283 impl_vtables.get_slice(subst::FnSpace));
288 /// Translates the adapter that deconstructs a `Box<Trait>` object into
289 /// `Trait` so that a by-value self method can be called.
290 pub fn trans_unboxing_shim(bcx: &Block,
291 llshimmedfn: ValueRef,
293 method_id: ast::DefId,
294 substs: subst::Substs)
296 let _icx = push_ctxt("trans_unboxing_shim");
300 // Transform the self type to `Box<self_type>`.
301 let self_type = *method.fty.sig.inputs.get(0);
302 let boxed_self_type = ty::mk_uniq(tcx, self_type);
303 let boxed_function_type = ty::FnSig {
304 binder_id: method.fty.sig.binder_id,
305 inputs: method.fty.sig.inputs.iter().enumerate().map(|(i, typ)| {
312 output: method.fty.sig.output,
315 let boxed_function_type = ty::BareFnTy {
316 fn_style: method.fty.fn_style,
318 sig: boxed_function_type,
320 let boxed_function_type =
321 ty::mk_bare_fn(tcx, boxed_function_type).subst(tcx, &substs);
323 ty::mk_bare_fn(tcx, method.fty.clone()).subst(tcx, &substs);
325 let function_name = ty::with_path(tcx, method_id, |path| {
326 link::mangle_internal_name_by_path_and_seq(path, "unboxing_shim")
328 let llfn = decl_internal_rust_fn(ccx,
330 function_name.as_slice());
332 let block_arena = TypedArena::new();
333 let empty_param_substs = param_substs::empty();
334 let return_type = ty::ty_fn_ret(boxed_function_type);
335 let fcx = new_fn_ctxt(ccx,
344 let mut bcx = init_function(&fcx, false, return_type);
346 // Create the substituted versions of the self type.
347 let arg_scope = fcx.push_custom_cleanup_scope();
348 let arg_scope_id = cleanup::CustomScope(arg_scope);
349 let boxed_arg_types = ty::ty_fn_args(boxed_function_type);
350 let boxed_self_type = *boxed_arg_types.get(0);
351 let arg_types = ty::ty_fn_args(function_type);
352 let self_type = *arg_types.get(0);
353 let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
355 // Create a datum for self.
356 let llboxedself = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
357 let llboxedself = Datum::new(llboxedself,
362 llboxedself.to_lvalue_datum_in_scope(bcx,
366 // This `Load` is needed because lvalue data are always by-ref.
367 let llboxedself = Load(bcx, boxed_self.val);
369 let llself = if type_is_immediate(ccx, self_type) {
370 let llboxedself = Load(bcx, llboxedself);
371 immediate_rvalue(llboxedself, self_type)
373 let llself = rvalue_scratch_datum(bcx, self_type, "self");
374 memcpy_ty(bcx, llself.val, llboxedself, self_type);
378 // Make sure we don't free the box twice!
379 boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type);
381 // Schedule a cleanup to free the box.
382 fcx.schedule_free_value(arg_scope_id,
384 cleanup::HeapExchange,
387 // Now call the function.
388 let mut llshimmedargs = vec!(llself.val);
389 for i in range(1, arg_types.len()) {
390 llshimmedargs.push(get_param(fcx.llfn, fcx.arg_pos(i) as u32));
392 bcx = trans_call_inner(bcx,
398 data: Fn(llshimmedfn),
401 ArgVals(llshimmedargs.as_slice()),
402 match fcx.llretptr.get() {
404 Some(llretptr) => Some(expr::SaveIn(llretptr)),
407 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
408 finish_fn(&fcx, bcx, return_type);
413 pub fn trans_fn_ref_with_vtables(
415 def_id: ast::DefId, // def id of fn
416 node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
417 substs: subst::Substs, // values for fn's ty params
418 vtables: typeck::vtable_res) // vtables for the call
422 * Translates a reference to a fn/method item, monomorphizing and
423 * inlining as it goes.
427 * - `bcx`: the current block where the reference to the fn occurs
428 * - `def_id`: def id of the fn or method item being referenced
429 * - `node`: node id of the reference to the fn/method, if applicable.
430 * This parameter may be zero; but, if so, the resulting value may not
431 * have the right type, so it must be cast before being used.
432 * - `substs`: values for each of the fn/method's parameters
433 * - `vtables`: values for each bound on each of the type parameters
436 let _icx = push_ctxt("trans_fn_ref_with_vtables");
440 debug!("trans_fn_ref_with_vtables(bcx={}, def_id={}, node={:?}, \
441 substs={}, vtables={})",
448 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
450 // Load the info for the appropriate trait if necessary.
451 match ty::trait_of_method(tcx, def_id) {
454 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
458 // We need to do a bunch of special handling for default methods.
459 // We need to modify the def_id and our substs in order to monomorphize
461 let (is_default, def_id, substs, vtables) =
462 match ty::provided_source(tcx, def_id) {
463 None => (false, def_id, substs, vtables),
465 // There are two relevant substitutions when compiling
466 // default methods. First, there is the substitution for
467 // the type parameters of the impl we are using and the
468 // method we are calling. This substitution is the substs
469 // argument we already have.
470 // In order to compile a default method, though, we need
471 // to consider another substitution: the substitution for
472 // the type parameters on trait; the impl we are using
473 // implements the trait at some particular type
474 // parameters, and we need to substitute for those first.
475 // So, what we need to do is find this substitution and
476 // compose it with the one we already have.
478 let impl_id = ty::method(tcx, def_id).container_id();
479 let method = ty::method(tcx, source_id);
480 let trait_ref = ty::impl_trait_ref(tcx, impl_id)
481 .expect("could not find trait_ref for impl with \
484 // Compute the first substitution
485 let first_subst = make_substs_for_receiver_types(
486 tcx, &*trait_ref, &*method);
489 let new_substs = first_subst.subst(tcx, &substs);
491 debug!("trans_fn_with_vtables - default method: \
492 substs = {}, trait_subst = {}, \
493 first_subst = {}, new_subst = {}, \
495 substs.repr(tcx), trait_ref.substs.repr(tcx),
496 first_subst.repr(tcx), new_substs.repr(tcx),
500 resolve_default_method_vtables(bcx, impl_id, &substs, vtables);
502 debug!("trans_fn_with_vtables - default method: \
504 param_vtables.repr(tcx));
506 (true, source_id, new_substs, param_vtables)
510 // If this is an unboxed closure, redirect to it.
511 match closure::get_or_create_declaration_if_unboxed_closure(ccx, def_id) {
513 Some(llfn) => return llfn,
516 // Check whether this fn has an inlined copy and, if so, redirect
517 // def_id to the local id of the inlined copy.
519 if def_id.krate != ast::LOCAL_CRATE {
520 inline::maybe_instantiate_inline(ccx, def_id)
526 // We must monomorphise if the fn has type parameters, is a default method,
527 // or is a named tuple constructor.
528 let must_monomorphise = if !substs.types.is_empty() || is_default {
530 } else if def_id.krate == ast::LOCAL_CRATE {
531 let map_node = session::expect(
533 tcx.map.find(def_id.node),
534 || "local item should be in ast map".to_string());
537 ast_map::NodeVariant(v) => match v.node.kind {
538 ast::TupleVariantKind(ref args) => args.len() > 0,
541 ast_map::NodeStructCtor(_) => true,
548 // Create a monomorphic version of generic functions
549 if must_monomorphise {
550 // Should be either intra-crate or inlined.
551 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
553 let opt_ref_id = match node {
554 ExprId(id) => if id != 0 { Some(id) } else { None },
555 MethodCall(_) => None,
558 let (val, must_cast) =
559 monomorphize::monomorphic_fn(ccx, def_id, &substs,
560 vtables, opt_ref_id);
562 if must_cast && node != ExprId(0) {
563 // Monotype of the REFERENCE to the function (type params
565 let ref_ty = match node {
566 ExprId(id) => node_id_type(bcx, id),
567 MethodCall(method_call) => {
568 let t = bcx.tcx().method_map.borrow().get(&method_call).ty;
569 monomorphize_type(bcx, t)
574 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
579 // Polytype of the function item (may have type params)
580 let fn_tpt = ty::lookup_item_type(tcx, def_id);
582 // Find the actual function pointer.
584 if def_id.krate == ast::LOCAL_CRATE {
585 // Internal reference.
586 get_item_val(ccx, def_id.node)
588 // External reference.
589 trans_external_path(ccx, def_id, fn_tpt.ty)
593 // This is subtle and surprising, but sometimes we have to bitcast
594 // the resulting fn pointer. The reason has to do with external
595 // functions. If you have two crates that both bind the same C
596 // library, they may not use precisely the same types: for
597 // example, they will probably each declare their own structs,
598 // which are distinct types from LLVM's point of view (nominal
601 // Now, if those two crates are linked into an application, and
602 // they contain inlined code, you can wind up with a situation
603 // where both of those functions wind up being loaded into this
604 // application simultaneously. In that case, the same function
605 // (from LLVM's point of view) requires two types. But of course
606 // LLVM won't allow one function to have two types.
608 // What we currently do, therefore, is declare the function with
609 // one of the two types (whichever happens to come first) and then
610 // bitcast as needed when the function is referenced to make sure
611 // it has the type we expect.
613 // This can occur on either a crate-local or crate-external
614 // reference. It also occurs when testing libcore and in some
615 // other weird situations. Annoying.
616 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
617 let llptrty = llty.ptr_to();
618 if val_ty(val) != llptrty {
619 debug!("trans_fn_ref_with_vtables(): casting pointer!");
620 val = BitCast(bcx, val, llptrty);
622 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
628 // ______________________________________________________________________
631 pub fn trans_call<'a>(
632 in_cx: &'a Block<'a>,
638 let _icx = push_ctxt("trans_call");
639 trans_call_inner(in_cx,
640 Some(common::expr_info(call_ex)),
642 |cx, _| trans(cx, f),
647 pub fn trans_method_call<'a>(
654 let _icx = push_ctxt("trans_method_call");
655 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
656 let method_call = MethodCall::expr(call_ex.id);
657 let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
660 Some(common::expr_info(call_ex)),
661 monomorphize_type(bcx, method_ty),
662 |cx, arg_cleanup_scope| {
663 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
669 pub fn trans_lang_call<'a>(
673 dest: Option<expr::Dest>)
675 let fty = if did.krate == ast::LOCAL_CRATE {
676 ty::node_id_to_type(bcx.tcx(), did.node)
678 csearch::get_type(bcx.tcx(), did).ty
680 callee::trans_call_inner(bcx,
684 trans_fn_ref_with_vtables_to_callee(bcx,
687 subst::Substs::empty(),
688 VecPerParamSpace::empty())
694 pub fn trans_call_inner<'a>(
696 call_info: Option<NodeInfo>,
698 get_callee: |bcx: &'a Block<'a>,
699 arg_cleanup_scope: cleanup::ScopeId|
702 dest: Option<expr::Dest>)
705 * This behemoth of a function translates function calls.
706 * Unfortunately, in order to generate more efficient LLVM
707 * output at -O0, it has quite a complex signature (refactoring
708 * this into two functions seems like a good idea).
710 * In particular, for lang items, it is invoked with a dest of
711 * None, and in that case the return value contains the result of
712 * the fn. The lang item must not return a structural type or else
713 * all heck breaks loose.
715 * For non-lang items, `dest` is always Some, and hence the result
716 * is written into memory somewhere. Nonetheless we return the
717 * actual return value of the function.
720 // Introduce a temporary cleanup scope that will contain cleanups
721 // for the arguments while they are being evaluated. The purpose
722 // this cleanup is to ensure that, should a failure occur while
723 // evaluating argument N, the values for arguments 0...N-1 are all
724 // cleaned up. If no failure occurs, the values are handed off to
725 // the callee, and hence none of the cleanups in this temporary
726 // scope will ever execute.
729 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
731 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
732 let mut bcx = callee.bcx;
734 let (abi, ret_ty) = match ty::get(callee_ty).sty {
735 ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
736 ty::ty_closure(ref f) => (f.abi, f.sig.output),
737 _ => fail!("expected bare rust fn or closure in trans_call_inner")
740 let (llfn, llenv, llself) = match callee.data {
745 (d.llfn, None, Some(d.llself))
748 // Closures are represented as (llfn, llclosure) pair:
749 // load the requisite values out.
750 let pair = d.to_llref();
751 let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
752 let llfn = Load(bcx, llfn);
753 let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
754 let llenv = Load(bcx, llenv);
755 (llfn, Some(llenv), None)
757 Intrinsic(node, substs) => {
758 assert!(abi == synabi::RustIntrinsic);
759 assert!(dest.is_some());
761 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
762 arg_cleanup_scope, args,
763 dest.unwrap(), substs);
765 NamedTupleConstructor(substs, disr) => {
766 assert!(dest.is_some());
767 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
769 let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
770 return base::trans_named_tuple_constructor(bcx, ctor_ty, disr,
771 args, dest.unwrap());
775 // Intrinsics should not become actual functions.
776 // We trans them in place in `trans_intrinsic_call`
777 assert!(abi != synabi::RustIntrinsic);
779 let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
781 // Generate a location to store the result. If the user does
782 // not care about the result, just make a stack slot.
783 let opt_llretslot = match dest {
785 assert!(!type_of::return_uses_outptr(ccx, ret_ty));
788 Some(expr::SaveIn(dst)) => Some(dst),
789 Some(expr::Ignore) if !is_rust_fn ||
790 type_of::return_uses_outptr(ccx, ret_ty) ||
791 ty::type_needs_drop(bcx.tcx(), ret_ty) => {
792 if !type_is_zero_size(ccx, ret_ty) {
793 Some(alloc_ty(bcx, ret_ty, "__llret"))
795 let llty = type_of::type_of(ccx, ret_ty);
796 Some(C_undef(llty.ptr_to()))
799 Some(expr::Ignore) => None
802 let mut llresult = unsafe {
803 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
806 // The code below invokes the function, using either the Rust
807 // conventions (if it is a rust fn) or the native conventions
808 // (otherwise). The important part is that, when all is sad
809 // and done, either the return value of the function will have been
810 // written in opt_llretslot (if it is Some) or `llresult` will be
811 // set appropriately (otherwise).
813 let mut llargs = Vec::new();
815 // Push the out-pointer if we use an out-pointer for this
816 // return type, otherwise push "undef".
817 if type_of::return_uses_outptr(ccx, ret_ty) {
818 llargs.push(opt_llretslot.unwrap());
821 // Push the environment (or a trait object's self).
822 match (llenv, llself) {
823 (Some(llenv), None) => {
826 (None, Some(llself)) => llargs.push(llself),
830 // Push the arguments.
831 bcx = trans_args(bcx,
835 cleanup::CustomScope(arg_cleanup_scope),
839 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
841 // Invoke the actual rust fn and update bcx/llresult.
842 let (llret, b) = base::invoke(bcx,
850 // If the Rust convention for this type is return via
851 // the return value, copy it into llretslot.
852 match opt_llretslot {
854 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
855 !type_is_zero_size(bcx.ccx(), ret_ty)
857 store_ty(bcx, llret, llretslot, ret_ty)
863 // Lang items are the only case where dest is None, and
864 // they are always Rust fns.
865 assert!(dest.is_some());
867 let mut llargs = Vec::new();
868 let arg_tys = match args {
869 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
870 _ => fail!("expected arg exprs.")
872 bcx = trans_args(bcx,
876 cleanup::CustomScope(arg_cleanup_scope),
879 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
880 bcx = foreign::trans_native_call(bcx, callee_ty,
881 llfn, opt_llretslot.unwrap(),
882 llargs.as_slice(), arg_tys);
885 // If the caller doesn't care about the result of this fn call,
886 // drop the temporary slot we made.
887 match (dest, opt_llretslot) {
888 (Some(expr::Ignore), Some(llretslot)) => {
889 // drop the value if it is not being saved.
890 bcx = glue::drop_ty(bcx, llretslot, ret_ty);
891 call_lifetime_end(bcx, llretslot);
896 if ty::type_is_bot(ret_ty) {
900 Result::new(bcx, llresult)
903 pub enum CallArgs<'a> {
904 // Supply value of arguments as a list of expressions that must be
905 // translated. This is used in the common case of `foo(bar, qux)`.
906 ArgExprs(&'a [Gc<ast::Expr>]),
908 // Supply value of arguments as a list of LLVM value refs; frequently
909 // used with lang items and so forth, when the argument is an internal
911 ArgVals(&'a [ValueRef]),
913 // For overloaded operators: `(lhs, Option(rhs, rhs_id))`. `lhs`
914 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
915 // the right-hand-side (if any).
916 ArgOverloadedOp(Datum<Expr>, Option<(Datum<Expr>, ast::NodeId)>),
918 // Supply value of arguments as a list of expressions that must be
919 // translated, for overloaded call operators.
920 ArgOverloadedCall(&'a [Gc<ast::Expr>]),
923 fn trans_args_under_call_abi<'a>(
924 mut bcx: &'a Block<'a>,
925 arg_exprs: &[Gc<ast::Expr>],
927 llargs: &mut Vec<ValueRef>,
928 arg_cleanup_scope: cleanup::ScopeId,
931 // Translate the `self` argument first.
932 let arg_tys = ty::ty_fn_args(fn_ty);
934 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
935 llargs.push(unpack_result!(bcx, {
944 // Now untuple the rest of the arguments.
945 let tuple_expr = arg_exprs[1];
946 let tuple_type = node_id_type(bcx, tuple_expr.id);
948 match ty::get(tuple_type).sty {
949 ty::ty_tup(ref field_types) => {
950 let tuple_datum = unpack_datum!(bcx,
951 expr::trans(bcx, &*tuple_expr));
952 let tuple_lvalue_datum =
954 tuple_datum.to_lvalue_datum(bcx,
957 let repr = adt::represent_type(bcx.ccx(), tuple_type);
958 let repr_ptr = &*repr;
959 for i in range(0, field_types.len()) {
960 let arg_datum = tuple_lvalue_datum.get_element(
963 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
965 let arg_datum = arg_datum.to_expr_datum();
967 unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
969 unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
970 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
975 bcx.sess().span_bug(tuple_expr.span,
976 "argument to `.call()` wasn't a tuple?!")
983 fn trans_overloaded_call_args<'a>(
984 mut bcx: &'a Block<'a>,
985 arg_exprs: &[Gc<ast::Expr>],
987 llargs: &mut Vec<ValueRef>,
988 arg_cleanup_scope: cleanup::ScopeId,
991 // Translate the `self` argument first.
992 let arg_tys = ty::ty_fn_args(fn_ty);
994 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
995 llargs.push(unpack_result!(bcx, {
1004 // Now untuple the rest of the arguments.
1005 let tuple_type = *arg_tys.get(1);
1006 match ty::get(tuple_type).sty {
1007 ty::ty_tup(ref field_types) => {
1008 for (i, &field_type) in field_types.iter().enumerate() {
1010 unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[i + 1]));
1011 llargs.push(unpack_result!(bcx, {
1012 trans_arg_datum(bcx,
1022 bcx.sess().span_bug(arg_exprs[0].span,
1023 "argument to `.call()` wasn't a tuple?!")
1030 pub fn trans_args<'a>(
1034 llargs: &mut Vec<ValueRef> ,
1035 arg_cleanup_scope: cleanup::ScopeId,
1039 debug!("trans_args(abi={})", abi);
1041 let _icx = push_ctxt("trans_args");
1042 let arg_tys = ty::ty_fn_args(fn_ty);
1043 let variadic = ty::fn_is_variadic(fn_ty);
1047 // First we figure out the caller's view of the types of the arguments.
1048 // This will be needed if this is a generic call, because the callee has
1049 // to cast her view of the arguments to the caller's view.
1051 ArgExprs(arg_exprs) => {
1052 if abi == synabi::RustCall {
1053 // This is only used for direct calls to the `call`,
1054 // `call_mut` or `call_once` functions.
1055 return trans_args_under_call_abi(cx,
1063 let num_formal_args = arg_tys.len();
1064 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1065 if i == 0 && ignore_self {
1068 let arg_ty = if i >= num_formal_args {
1070 expr_ty_adjusted(cx, &**arg_expr)
1075 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1076 llargs.push(unpack_result!(bcx, {
1077 trans_arg_datum(bcx, arg_ty, arg_datum,
1083 ArgOverloadedCall(arg_exprs) => {
1084 return trans_overloaded_call_args(cx,
1091 ArgOverloadedOp(lhs, rhs) => {
1094 llargs.push(unpack_result!(bcx, {
1095 trans_arg_datum(bcx, *arg_tys.get(0), lhs,
1101 Some((rhs, rhs_id)) => {
1102 assert_eq!(arg_tys.len(), 2);
1104 llargs.push(unpack_result!(bcx, {
1105 trans_arg_datum(bcx, *arg_tys.get(1), rhs,
1107 DoAutorefArg(rhs_id))
1110 None => assert_eq!(arg_tys.len(), 1)
1114 llargs.push_all(vs);
1121 pub enum AutorefArg {
1123 DoAutorefArg(ast::NodeId)
1126 pub fn trans_arg_datum<'a>(
1128 formal_arg_ty: ty::t,
1129 arg_datum: Datum<Expr>,
1130 arg_cleanup_scope: cleanup::ScopeId,
1131 autoref_arg: AutorefArg)
1133 let _icx = push_ctxt("trans_arg_datum");
1135 let ccx = bcx.ccx();
1137 debug!("trans_arg_datum({})",
1138 formal_arg_ty.repr(bcx.tcx()));
1140 let arg_datum_ty = arg_datum.ty;
1142 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1145 if ty::type_is_bot(arg_datum_ty) {
1146 // For values of type _|_, we generate an
1147 // "undef" value, as such a value should never
1148 // be inspected. It's important for the value
1149 // to have type lldestty (the callee's expected type).
1150 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1152 val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
1155 // FIXME(#3548) use the adjustments table
1157 DoAutorefArg(arg_id) => {
1158 // We will pass argument by reference
1159 // We want an lvalue, so that we can pass by reference and
1160 let arg_datum = unpack_datum!(
1161 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1162 val = arg_datum.val;
1165 // Make this an rvalue, since we are going to be
1166 // passing ownership.
1167 let arg_datum = unpack_datum!(
1168 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1170 // Now that arg_datum is owned, get it into the appropriate
1171 // mode (ref vs value).
1172 let arg_datum = unpack_datum!(
1173 bcx, arg_datum.to_appropriate_datum(bcx));
1175 // Technically, ownership of val passes to the callee.
1176 // However, we must cleanup should we fail before the
1177 // callee is actually invoked.
1178 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1182 if formal_arg_ty != arg_datum_ty {
1183 // this could happen due to e.g. subtyping
1184 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1185 debug!("casting actual type ({}) to match formal ({})",
1186 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1187 val = PointerCast(bcx, val, llformal_arg_ty);
1191 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1192 Result::new(bcx, val)