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;
22 use llvm::{ValueRef, get_param};
24 use metadata::csearch;
27 use middle::subst::{Subst, VecPerParamSpace};
28 use middle::trans::adt;
29 use middle::trans::base;
30 use middle::trans::base::*;
31 use middle::trans::build::*;
32 use middle::trans::callee;
33 use middle::trans::cleanup;
34 use middle::trans::cleanup::CleanupMethods;
35 use middle::trans::closure;
36 use middle::trans::common;
37 use middle::trans::common::*;
38 use middle::trans::datum::*;
39 use middle::trans::datum::{Datum, KindOps};
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;
51 use middle::typeck::coherence::make_substs_for_receiver_types;
52 use middle::typeck::MethodCall;
53 use util::ppaux::Repr;
57 use synabi = syntax::abi;
59 pub struct MethodData {
65 Closure(Datum<Lvalue>),
67 // Represents a (possibly monomorphized) top-level fn item or method
68 // item. Note that this is just the fn-ptr and is not a Rust closure
69 // value (which is a pair).
70 Fn(/* llfn */ ValueRef),
72 Intrinsic(ast::NodeId, subst::Substs),
74 TraitMethod(MethodData)
77 pub struct Callee<'a> {
78 pub bcx: &'a Block<'a>,
82 fn trans<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
83 let _icx = push_ctxt("trans_callee");
84 debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
86 // pick out special kinds of expressions that can be called:
89 return trans_def(bcx, bcx.def(expr.id), expr);
94 // any other expressions are closures:
95 return datum_callee(bcx, expr);
97 fn datum_callee<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
98 let DatumBlock {bcx: mut bcx, datum} = expr::trans(bcx, expr);
99 match ty::get(datum.ty).sty {
100 ty::ty_bare_fn(..) => {
101 let llval = datum.to_llscalarish(bcx);
107 ty::ty_closure(..) => {
108 let datum = unpack_datum!(
109 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
112 data: Closure(datum),
116 bcx.tcx().sess.span_bug(
118 format!("type of callee is neither bare-fn nor closure: \
120 bcx.ty_to_string(datum.ty)).as_slice());
125 fn fn_callee<'a>(bcx: &'a Block<'a>, llfn: ValueRef) -> Callee<'a> {
132 fn trans_def<'a>(bcx: &'a Block<'a>, def: def::Def, ref_expr: &ast::Expr)
134 debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
135 let expr_ty = node_id_type(bcx, ref_expr.id);
137 def::DefFn(did, _) if match ty::get(expr_ty).sty {
138 ty::ty_bare_fn(ref f) => f.abi == synabi::RustIntrinsic,
141 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
142 let def_id = if did.krate != ast::LOCAL_CRATE {
143 inline::maybe_instantiate_inline(bcx.ccx(), did)
147 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
150 def::DefStaticMethod(did, def::FromImpl(_), _) => {
151 fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
153 def::DefStaticMethod(impl_did,
154 def::FromTrait(trait_did),
156 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
160 def::DefVariant(tid, vid, _) => {
161 // nullary variants are not callable
162 assert!(ty::enum_variant_with_id(bcx.tcx(),
164 vid).args.len() > 0u);
165 fn_callee(bcx, trans_fn_ref(bcx, vid, ExprId(ref_expr.id)))
167 def::DefStruct(def_id) => {
168 fn_callee(bcx, trans_fn_ref(bcx, def_id, ExprId(ref_expr.id)))
173 def::DefBinding(..) |
174 def::DefUpvar(..) => {
175 datum_callee(bcx, ref_expr)
177 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
178 def::DefTy(..) | def::DefPrimTy(..) |
179 def::DefUse(..) | def::DefTyParamBinder(..) |
180 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
181 def::DefSelfTy(..) | def::DefMethod(..) => {
182 bcx.tcx().sess.span_bug(
184 format!("cannot translate def {:?} \
185 to a callable thing!", def).as_slice());
191 pub fn trans_fn_ref(bcx: &Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
193 * Translates a reference (with id `ref_id`) to the fn/method
194 * with id `def_id` into a function pointer. This may require
195 * monomorphization or inlining.
198 let _icx = push_ctxt("trans_fn_ref");
200 let substs = node_id_substs(bcx, node);
201 let vtable_key = match node {
202 ExprId(id) => MethodCall::expr(id),
203 MethodCall(method_call) => method_call
205 let vtables = node_vtables(bcx, vtable_key);
206 debug!("trans_fn_ref(def_id={}, node={:?}, substs={}, vtables={})",
207 def_id.repr(bcx.tcx()),
209 substs.repr(bcx.tcx()),
210 vtables.repr(bcx.tcx()));
211 trans_fn_ref_with_vtables(bcx, def_id, node, substs, vtables)
214 fn trans_fn_ref_with_vtables_to_callee<'a>(bcx: &'a Block<'a>,
217 substs: subst::Substs,
218 vtables: typeck::vtable_res)
222 data: Fn(trans_fn_ref_with_vtables(bcx,
230 fn resolve_default_method_vtables(bcx: &Block,
232 substs: &subst::Substs,
233 impl_vtables: typeck::vtable_res)
234 -> typeck::vtable_res
236 // Get the vtables that the impl implements the trait at
237 let impl_res = ty::lookup_impl_vtables(bcx.tcx(), impl_id);
239 // Build up a param_substs that we are going to resolve the
240 // trait_vtables under.
241 let param_substs = param_substs {
242 substs: (*substs).clone(),
243 vtables: impl_vtables.clone()
246 let mut param_vtables = resolve_vtables_under_param_substs(
247 bcx.tcx(), ¶m_substs, &impl_res);
249 // Now we pull any vtables for parameters on the actual method.
250 param_vtables.push_all(subst::FnSpace,
251 impl_vtables.get_slice(subst::FnSpace));
256 /// Translates the adapter that deconstructs a `Box<Trait>` object into
257 /// `Trait` so that a by-value self method can be called.
258 pub fn trans_unboxing_shim(bcx: &Block,
259 llshimmedfn: ValueRef,
261 method_id: ast::DefId,
262 substs: subst::Substs)
264 let _icx = push_ctxt("trans_unboxing_shim");
268 // Transform the self type to `Box<self_type>`.
269 let self_type = *method.fty.sig.inputs.get(0);
270 let boxed_self_type = ty::mk_uniq(tcx, self_type);
271 let boxed_function_type = ty::FnSig {
272 binder_id: method.fty.sig.binder_id,
273 inputs: method.fty.sig.inputs.iter().enumerate().map(|(i, typ)| {
280 output: method.fty.sig.output,
283 let boxed_function_type = ty::BareFnTy {
284 fn_style: method.fty.fn_style,
286 sig: boxed_function_type,
288 let boxed_function_type =
289 ty::mk_bare_fn(tcx, boxed_function_type).subst(tcx, &substs);
291 ty::mk_bare_fn(tcx, method.fty.clone()).subst(tcx, &substs);
293 let function_name = ty::with_path(tcx, method_id, |path| {
294 link::mangle_internal_name_by_path_and_seq(path, "unboxing_shim")
296 let llfn = decl_internal_rust_fn(ccx,
298 function_name.as_slice());
300 let block_arena = TypedArena::new();
301 let empty_param_substs = param_substs::empty();
302 let return_type = ty::ty_fn_ret(boxed_function_type);
303 let fcx = new_fn_ctxt(ccx,
311 let mut bcx = init_function(&fcx, false, return_type);
313 // Create the substituted versions of the self type.
314 let arg_scope = fcx.push_custom_cleanup_scope();
315 let arg_scope_id = cleanup::CustomScope(arg_scope);
316 let boxed_arg_types = ty::ty_fn_args(boxed_function_type);
317 let boxed_self_type = *boxed_arg_types.get(0);
318 let arg_types = ty::ty_fn_args(function_type);
319 let self_type = *arg_types.get(0);
320 let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
322 // Create a datum for self.
323 let llboxedself = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
324 let llboxedself = Datum::new(llboxedself,
329 llboxedself.to_lvalue_datum_in_scope(bcx,
333 // This `Load` is needed because lvalue data are always by-ref.
334 let llboxedself = Load(bcx, boxed_self.val);
336 let llself = if type_is_immediate(ccx, self_type) {
337 let llboxedself = Load(bcx, llboxedself);
338 immediate_rvalue(llboxedself, self_type)
340 let llself = rvalue_scratch_datum(bcx, self_type, "self");
341 memcpy_ty(bcx, llself.val, llboxedself, self_type);
345 // Make sure we don't free the box twice!
346 boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type);
348 // Schedule a cleanup to free the box.
349 fcx.schedule_free_value(arg_scope_id,
351 cleanup::HeapExchange,
354 // Now call the function.
355 let mut llshimmedargs = vec!(llself.val);
356 for i in range(1, arg_types.len()) {
357 llshimmedargs.push(get_param(fcx.llfn, fcx.arg_pos(i) as u32));
359 bcx = trans_call_inner(bcx,
365 data: Fn(llshimmedfn),
368 ArgVals(llshimmedargs.as_slice()),
369 match fcx.llretptr.get() {
371 Some(llretptr) => Some(expr::SaveIn(llretptr)),
374 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
375 finish_fn(&fcx, bcx, return_type);
380 pub fn trans_fn_ref_with_vtables(
382 def_id: ast::DefId, // def id of fn
383 node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
384 substs: subst::Substs, // values for fn's ty params
385 vtables: typeck::vtable_res) // vtables for the call
389 * Translates a reference to a fn/method item, monomorphizing and
390 * inlining as it goes.
394 * - `bcx`: the current block where the reference to the fn occurs
395 * - `def_id`: def id of the fn or method item being referenced
396 * - `node`: node id of the reference to the fn/method, if applicable.
397 * This parameter may be zero; but, if so, the resulting value may not
398 * have the right type, so it must be cast before being used.
399 * - `substs`: values for each of the fn/method's parameters
400 * - `vtables`: values for each bound on each of the type parameters
403 let _icx = push_ctxt("trans_fn_ref_with_vtables");
407 debug!("trans_fn_ref_with_vtables(bcx={}, def_id={}, node={:?}, \
408 substs={}, vtables={})",
415 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
417 // Load the info for the appropriate trait if necessary.
418 match ty::trait_of_method(tcx, def_id) {
421 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
425 // We need to do a bunch of special handling for default methods.
426 // We need to modify the def_id and our substs in order to monomorphize
428 let (is_default, def_id, substs, vtables) =
429 match ty::provided_source(tcx, def_id) {
430 None => (false, def_id, substs, vtables),
432 // There are two relevant substitutions when compiling
433 // default methods. First, there is the substitution for
434 // the type parameters of the impl we are using and the
435 // method we are calling. This substitution is the substs
436 // argument we already have.
437 // In order to compile a default method, though, we need
438 // to consider another substitution: the substitution for
439 // the type parameters on trait; the impl we are using
440 // implements the trait at some particular type
441 // parameters, and we need to substitute for those first.
442 // So, what we need to do is find this substitution and
443 // compose it with the one we already have.
445 let impl_id = ty::method(tcx, def_id).container_id();
446 let method = ty::method(tcx, source_id);
447 let trait_ref = ty::impl_trait_ref(tcx, impl_id)
448 .expect("could not find trait_ref for impl with \
451 // Compute the first substitution
452 let first_subst = make_substs_for_receiver_types(
453 tcx, &*trait_ref, &*method);
456 let new_substs = first_subst.subst(tcx, &substs);
458 debug!("trans_fn_with_vtables - default method: \
459 substs = {}, trait_subst = {}, \
460 first_subst = {}, new_subst = {}, \
462 substs.repr(tcx), trait_ref.substs.repr(tcx),
463 first_subst.repr(tcx), new_substs.repr(tcx),
467 resolve_default_method_vtables(bcx, impl_id, &substs, vtables);
469 debug!("trans_fn_with_vtables - default method: \
471 param_vtables.repr(tcx));
473 (true, source_id, new_substs, param_vtables)
477 // If this is an unboxed closure, redirect to it.
478 match closure::get_or_create_declaration_if_unboxed_closure(ccx, def_id) {
480 Some(llfn) => return llfn,
483 // Check whether this fn has an inlined copy and, if so, redirect
484 // def_id to the local id of the inlined copy.
486 if def_id.krate != ast::LOCAL_CRATE {
487 inline::maybe_instantiate_inline(ccx, def_id)
493 // We must monomorphise if the fn has type parameters or is a default method.
494 let must_monomorphise = !substs.types.is_empty() || is_default;
496 // Create a monomorphic version of generic functions
497 if must_monomorphise {
498 // Should be either intra-crate or inlined.
499 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
501 let opt_ref_id = match node {
502 ExprId(id) => if id != 0 { Some(id) } else { None },
503 MethodCall(_) => None,
506 let (val, must_cast) =
507 monomorphize::monomorphic_fn(ccx, def_id, &substs,
508 vtables, opt_ref_id);
510 if must_cast && node != ExprId(0) {
511 // Monotype of the REFERENCE to the function (type params
513 let ref_ty = match node {
514 ExprId(id) => node_id_type(bcx, id),
515 MethodCall(method_call) => {
516 let t = bcx.tcx().method_map.borrow().get(&method_call).ty;
517 monomorphize_type(bcx, t)
522 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
527 // Polytype of the function item (may have type params)
528 let fn_tpt = ty::lookup_item_type(tcx, def_id);
530 // Find the actual function pointer.
532 if def_id.krate == ast::LOCAL_CRATE {
533 // Internal reference.
534 get_item_val(ccx, def_id.node)
536 // External reference.
537 trans_external_path(ccx, def_id, fn_tpt.ty)
541 // This is subtle and surprising, but sometimes we have to bitcast
542 // the resulting fn pointer. The reason has to do with external
543 // functions. If you have two crates that both bind the same C
544 // library, they may not use precisely the same types: for
545 // example, they will probably each declare their own structs,
546 // which are distinct types from LLVM's point of view (nominal
549 // Now, if those two crates are linked into an application, and
550 // they contain inlined code, you can wind up with a situation
551 // where both of those functions wind up being loaded into this
552 // application simultaneously. In that case, the same function
553 // (from LLVM's point of view) requires two types. But of course
554 // LLVM won't allow one function to have two types.
556 // What we currently do, therefore, is declare the function with
557 // one of the two types (whichever happens to come first) and then
558 // bitcast as needed when the function is referenced to make sure
559 // it has the type we expect.
561 // This can occur on either a crate-local or crate-external
562 // reference. It also occurs when testing libcore and in some
563 // other weird situations. Annoying.
564 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
565 let llptrty = llty.ptr_to();
566 if val_ty(val) != llptrty {
567 debug!("trans_fn_ref_with_vtables(): casting pointer!");
568 val = BitCast(bcx, val, llptrty);
570 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
576 // ______________________________________________________________________
579 pub fn trans_call<'a>(
580 in_cx: &'a Block<'a>,
586 let _icx = push_ctxt("trans_call");
587 trans_call_inner(in_cx,
588 Some(common::expr_info(call_ex)),
590 |cx, _| trans(cx, f),
595 pub fn trans_method_call<'a>(
602 let _icx = push_ctxt("trans_method_call");
603 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
604 let method_call = MethodCall::expr(call_ex.id);
605 let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
608 Some(common::expr_info(call_ex)),
609 monomorphize_type(bcx, method_ty),
610 |cx, arg_cleanup_scope| {
611 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
617 pub fn trans_lang_call<'a>(
621 dest: Option<expr::Dest>)
623 let fty = if did.krate == ast::LOCAL_CRATE {
624 ty::node_id_to_type(bcx.tcx(), did.node)
626 csearch::get_type(bcx.tcx(), did).ty
628 callee::trans_call_inner(bcx,
632 trans_fn_ref_with_vtables_to_callee(bcx,
635 subst::Substs::empty(),
636 VecPerParamSpace::empty())
642 pub fn trans_call_inner<'a>(
644 call_info: Option<NodeInfo>,
646 get_callee: |bcx: &'a Block<'a>,
647 arg_cleanup_scope: cleanup::ScopeId|
650 dest: Option<expr::Dest>)
653 * This behemoth of a function translates function calls.
654 * Unfortunately, in order to generate more efficient LLVM
655 * output at -O0, it has quite a complex signature (refactoring
656 * this into two functions seems like a good idea).
658 * In particular, for lang items, it is invoked with a dest of
659 * None, and in that case the return value contains the result of
660 * the fn. The lang item must not return a structural type or else
661 * all heck breaks loose.
663 * For non-lang items, `dest` is always Some, and hence the result
664 * is written into memory somewhere. Nonetheless we return the
665 * actual return value of the function.
668 // Introduce a temporary cleanup scope that will contain cleanups
669 // for the arguments while they are being evaluated. The purpose
670 // this cleanup is to ensure that, should a failure occur while
671 // evaluating argument N, the values for arguments 0...N-1 are all
672 // cleaned up. If no failure occurs, the values are handed off to
673 // the callee, and hence none of the cleanups in this temporary
674 // scope will ever execute.
677 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
679 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
680 let mut bcx = callee.bcx;
682 let (abi, ret_ty) = match ty::get(callee_ty).sty {
683 ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
684 ty::ty_closure(ref f) => (f.abi, f.sig.output),
685 _ => fail!("expected bare rust fn or closure in trans_call_inner")
688 let (llfn, llenv, llself) = match callee.data {
693 (d.llfn, None, Some(d.llself))
696 // Closures are represented as (llfn, llclosure) pair:
697 // load the requisite values out.
698 let pair = d.to_llref();
699 let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
700 let llfn = Load(bcx, llfn);
701 let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
702 let llenv = Load(bcx, llenv);
703 (llfn, Some(llenv), None)
705 Intrinsic(node, substs) => {
706 assert!(abi == synabi::RustIntrinsic);
707 assert!(dest.is_some());
709 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
710 arg_cleanup_scope, args,
711 dest.unwrap(), substs);
715 // Intrinsics should not become actual functions.
716 // We trans them in place in `trans_intrinsic_call`
717 assert!(abi != synabi::RustIntrinsic);
719 // Generate a location to store the result. If the user does
720 // not care about the result, just make a stack slot.
721 let opt_llretslot = match dest {
723 assert!(!type_of::return_uses_outptr(ccx, ret_ty));
726 Some(expr::SaveIn(dst)) => Some(dst),
727 Some(expr::Ignore) => {
728 if !type_is_zero_size(ccx, ret_ty) {
729 Some(alloc_ty(bcx, ret_ty, "__llret"))
731 let llty = type_of::type_of(ccx, ret_ty);
732 Some(C_undef(llty.ptr_to()))
737 let mut llresult = unsafe {
738 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
741 // The code below invokes the function, using either the Rust
742 // conventions (if it is a rust fn) or the native conventions
743 // (otherwise). The important part is that, when all is sad
744 // and done, either the return value of the function will have been
745 // written in opt_llretslot (if it is Some) or `llresult` will be
746 // set appropriately (otherwise).
747 if abi == synabi::Rust || abi == synabi::RustCall {
748 let mut llargs = Vec::new();
750 // Push the out-pointer if we use an out-pointer for this
751 // return type, otherwise push "undef".
752 if type_of::return_uses_outptr(ccx, ret_ty) {
753 llargs.push(opt_llretslot.unwrap());
756 // Push the environment (or a trait object's self).
757 match (llenv, llself) {
758 (Some(llenv), None) => {
761 (None, Some(llself)) => llargs.push(llself),
765 // Push the arguments.
766 bcx = trans_args(bcx,
770 cleanup::CustomScope(arg_cleanup_scope),
774 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
776 // Invoke the actual rust fn and update bcx/llresult.
777 let (llret, b) = base::invoke(bcx,
785 // If the Rust convention for this type is return via
786 // the return value, copy it into llretslot.
787 match opt_llretslot {
789 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
790 !type_is_zero_size(bcx.ccx(), ret_ty)
792 store_ty(bcx, llret, llretslot, ret_ty)
798 // Lang items are the only case where dest is None, and
799 // they are always Rust fns.
800 assert!(dest.is_some());
802 let mut llargs = Vec::new();
803 let arg_tys = match args {
804 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
805 _ => fail!("expected arg exprs.")
807 bcx = trans_args(bcx,
811 cleanup::CustomScope(arg_cleanup_scope),
814 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
815 bcx = foreign::trans_native_call(bcx, callee_ty,
816 llfn, opt_llretslot.unwrap(),
817 llargs.as_slice(), arg_tys);
820 // If the caller doesn't care about the result of this fn call,
821 // drop the temporary slot we made.
824 assert!(!type_of::return_uses_outptr(bcx.ccx(), ret_ty));
826 Some(expr::Ignore) => {
827 // drop the value if it is not being saved.
828 bcx = glue::drop_ty(bcx, opt_llretslot.unwrap(), ret_ty);
830 Some(expr::SaveIn(_)) => { }
833 if ty::type_is_bot(ret_ty) {
837 Result::new(bcx, llresult)
840 pub enum CallArgs<'a> {
841 // Supply value of arguments as a list of expressions that must be
842 // translated. This is used in the common case of `foo(bar, qux)`.
843 ArgExprs(&'a [Gc<ast::Expr>]),
845 // Supply value of arguments as a list of LLVM value refs; frequently
846 // used with lang items and so forth, when the argument is an internal
848 ArgVals(&'a [ValueRef]),
850 // For overloaded operators: `(lhs, Option(rhs, rhs_id))`. `lhs`
851 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
852 // the right-hand-side (if any).
853 ArgOverloadedOp(Datum<Expr>, Option<(Datum<Expr>, ast::NodeId)>),
855 // Supply value of arguments as a list of expressions that must be
856 // translated, for overloaded call operators.
857 ArgOverloadedCall(&'a [Gc<ast::Expr>]),
860 fn trans_args_under_call_abi<'a>(
861 mut bcx: &'a Block<'a>,
862 arg_exprs: &[Gc<ast::Expr>],
864 llargs: &mut Vec<ValueRef>,
865 arg_cleanup_scope: cleanup::ScopeId,
868 // Translate the `self` argument first.
869 let arg_tys = ty::ty_fn_args(fn_ty);
871 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
872 llargs.push(unpack_result!(bcx, {
881 // Now untuple the rest of the arguments.
882 let tuple_expr = arg_exprs[1];
883 let tuple_type = node_id_type(bcx, tuple_expr.id);
885 match ty::get(tuple_type).sty {
886 ty::ty_tup(ref field_types) => {
887 let tuple_datum = unpack_datum!(bcx,
888 expr::trans(bcx, &*tuple_expr));
889 let tuple_lvalue_datum =
891 tuple_datum.to_lvalue_datum(bcx,
894 let repr = adt::represent_type(bcx.ccx(), tuple_type);
895 let repr_ptr = &*repr;
896 for i in range(0, field_types.len()) {
897 let arg_datum = tuple_lvalue_datum.get_element(
900 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
902 let arg_datum = arg_datum.to_expr_datum();
904 unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
906 unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
907 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
912 bcx.sess().span_bug(tuple_expr.span,
913 "argument to `.call()` wasn't a tuple?!")
920 fn trans_overloaded_call_args<'a>(
921 mut bcx: &'a Block<'a>,
922 arg_exprs: &[Gc<ast::Expr>],
924 llargs: &mut Vec<ValueRef>,
925 arg_cleanup_scope: cleanup::ScopeId,
928 // Translate the `self` argument first.
929 let arg_tys = ty::ty_fn_args(fn_ty);
931 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
932 llargs.push(unpack_result!(bcx, {
941 // Now untuple the rest of the arguments.
942 let tuple_type = *arg_tys.get(1);
943 match ty::get(tuple_type).sty {
944 ty::ty_tup(ref field_types) => {
945 for (i, &field_type) in field_types.iter().enumerate() {
947 unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[i + 1]));
948 llargs.push(unpack_result!(bcx, {
959 bcx.sess().span_bug(arg_exprs[0].span,
960 "argument to `.call()` wasn't a tuple?!")
967 pub fn trans_args<'a>(
971 llargs: &mut Vec<ValueRef> ,
972 arg_cleanup_scope: cleanup::ScopeId,
976 debug!("trans_args(abi={})", abi);
978 let _icx = push_ctxt("trans_args");
979 let arg_tys = ty::ty_fn_args(fn_ty);
980 let variadic = ty::fn_is_variadic(fn_ty);
984 // First we figure out the caller's view of the types of the arguments.
985 // This will be needed if this is a generic call, because the callee has
986 // to cast her view of the arguments to the caller's view.
988 ArgExprs(arg_exprs) => {
989 if abi == synabi::RustCall {
990 // This is only used for direct calls to the `call`,
991 // `call_mut` or `call_once` functions.
992 return trans_args_under_call_abi(cx,
1000 let num_formal_args = arg_tys.len();
1001 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1002 if i == 0 && ignore_self {
1005 let arg_ty = if i >= num_formal_args {
1007 expr_ty_adjusted(cx, &**arg_expr)
1012 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1013 llargs.push(unpack_result!(bcx, {
1014 trans_arg_datum(bcx, arg_ty, arg_datum,
1020 ArgOverloadedCall(arg_exprs) => {
1021 return trans_overloaded_call_args(cx,
1028 ArgOverloadedOp(lhs, rhs) => {
1031 llargs.push(unpack_result!(bcx, {
1032 trans_arg_datum(bcx, *arg_tys.get(0), lhs,
1038 Some((rhs, rhs_id)) => {
1039 assert_eq!(arg_tys.len(), 2);
1041 llargs.push(unpack_result!(bcx, {
1042 trans_arg_datum(bcx, *arg_tys.get(1), rhs,
1044 DoAutorefArg(rhs_id))
1047 None => assert_eq!(arg_tys.len(), 1)
1051 llargs.push_all(vs);
1058 pub enum AutorefArg {
1060 DoAutorefArg(ast::NodeId)
1063 pub fn trans_arg_datum<'a>(
1065 formal_arg_ty: ty::t,
1066 arg_datum: Datum<Expr>,
1067 arg_cleanup_scope: cleanup::ScopeId,
1068 autoref_arg: AutorefArg)
1070 let _icx = push_ctxt("trans_arg_datum");
1072 let ccx = bcx.ccx();
1074 debug!("trans_arg_datum({})",
1075 formal_arg_ty.repr(bcx.tcx()));
1077 let arg_datum_ty = arg_datum.ty;
1079 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1082 if ty::type_is_bot(arg_datum_ty) {
1083 // For values of type _|_, we generate an
1084 // "undef" value, as such a value should never
1085 // be inspected. It's important for the value
1086 // to have type lldestty (the callee's expected type).
1087 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1089 val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
1092 // FIXME(#3548) use the adjustments table
1094 DoAutorefArg(arg_id) => {
1095 // We will pass argument by reference
1096 // We want an lvalue, so that we can pass by reference and
1097 let arg_datum = unpack_datum!(
1098 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1099 val = arg_datum.val;
1102 // Make this an rvalue, since we are going to be
1103 // passing ownership.
1104 let arg_datum = unpack_datum!(
1105 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1107 // Now that arg_datum is owned, get it into the appropriate
1108 // mode (ref vs value).
1109 let arg_datum = unpack_datum!(
1110 bcx, arg_datum.to_appropriate_datum(bcx));
1112 // Technically, ownership of val passes to the callee.
1113 // However, we must cleanup should we fail before the
1114 // callee is actually invoked.
1115 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1119 if formal_arg_ty != arg_datum_ty {
1120 // this could happen due to e.g. subtyping
1121 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1122 debug!("casting actual type ({}) to match formal ({})",
1123 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1124 val = PointerCast(bcx, val, llformal_arg_ty);
1128 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1129 Result::new(bcx, val)