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 lib::llvm::ValueRef;
25 use metadata::csearch;
28 use middle::subst::{Subst, VecPerParamSpace};
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::common;
36 use middle::trans::common::*;
37 use middle::trans::datum::*;
38 use middle::trans::datum::{Datum, KindOps};
39 use middle::trans::expr;
40 use middle::trans::glue;
41 use middle::trans::inline;
42 use middle::trans::foreign;
43 use middle::trans::intrinsic;
44 use middle::trans::meth;
45 use middle::trans::monomorphize;
46 use middle::trans::type_::Type;
47 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;
56 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);
102 return Callee {bcx: bcx, data: Fn(llval)};
104 ty::ty_closure(..) => {
105 let datum = unpack_datum!(
106 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
107 return Callee {bcx: bcx, data: Closure(datum)};
110 bcx.tcx().sess.span_bug(
112 format!("type of callee is neither bare-fn nor closure: \
114 bcx.ty_to_string(datum.ty)).as_slice());
119 fn fn_callee<'a>(bcx: &'a Block<'a>, llfn: ValueRef) -> Callee<'a> {
120 return Callee {bcx: bcx, data: Fn(llfn)};
123 fn trans_def<'a>(bcx: &'a Block<'a>, def: def::Def, ref_expr: &ast::Expr)
125 debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
126 let expr_ty = node_id_type(bcx, ref_expr.id);
128 def::DefFn(did, _) if match ty::get(expr_ty).sty {
129 ty::ty_bare_fn(ref f) => f.abi == synabi::RustIntrinsic,
132 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
133 let def_id = if did.krate != ast::LOCAL_CRATE {
134 inline::maybe_instantiate_inline(bcx.ccx(), did)
138 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
141 def::DefStaticMethod(did, def::FromImpl(_), _) => {
142 fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
144 def::DefStaticMethod(impl_did,
145 def::FromTrait(trait_did),
147 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
151 def::DefVariant(tid, vid, _) => {
152 // nullary variants are not callable
153 assert!(ty::enum_variant_with_id(bcx.tcx(),
155 vid).args.len() > 0u);
156 fn_callee(bcx, trans_fn_ref(bcx, vid, ExprId(ref_expr.id)))
158 def::DefStruct(def_id) => {
159 fn_callee(bcx, trans_fn_ref(bcx, def_id, ExprId(ref_expr.id)))
164 def::DefBinding(..) |
165 def::DefUpvar(..) => {
166 datum_callee(bcx, ref_expr)
168 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
169 def::DefTy(..) | def::DefPrimTy(..) |
170 def::DefUse(..) | def::DefTyParamBinder(..) |
171 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
172 def::DefSelfTy(..) | def::DefMethod(..) => {
173 bcx.tcx().sess.span_bug(
175 format!("cannot translate def {:?} \
176 to a callable thing!", def).as_slice());
182 pub fn trans_fn_ref(bcx: &Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
184 * Translates a reference (with id `ref_id`) to the fn/method
185 * with id `def_id` into a function pointer. This may require
186 * monomorphization or inlining.
189 let _icx = push_ctxt("trans_fn_ref");
191 let substs = node_id_substs(bcx, node);
192 let vtable_key = match node {
193 ExprId(id) => MethodCall::expr(id),
194 MethodCall(method_call) => method_call
196 let vtables = node_vtables(bcx, vtable_key);
197 debug!("trans_fn_ref(def_id={}, node={:?}, substs={}, vtables={})",
198 def_id.repr(bcx.tcx()),
200 substs.repr(bcx.tcx()),
201 vtables.repr(bcx.tcx()));
202 trans_fn_ref_with_vtables(bcx, def_id, node, substs, vtables)
205 fn trans_fn_ref_with_vtables_to_callee<'a>(bcx: &'a Block<'a>,
208 substs: subst::Substs,
209 vtables: typeck::vtable_res)
212 data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ExprId(ref_id),
216 fn resolve_default_method_vtables(bcx: &Block,
218 substs: &subst::Substs,
219 impl_vtables: typeck::vtable_res)
220 -> typeck::vtable_res
222 // Get the vtables that the impl implements the trait at
223 let impl_res = ty::lookup_impl_vtables(bcx.tcx(), impl_id);
225 // Build up a param_substs that we are going to resolve the
226 // trait_vtables under.
227 let param_substs = param_substs {
228 substs: (*substs).clone(),
229 vtables: impl_vtables.clone()
232 let mut param_vtables = resolve_vtables_under_param_substs(
233 bcx.tcx(), ¶m_substs, &impl_res);
235 // Now we pull any vtables for parameters on the actual method.
236 param_vtables.push_all(subst::FnSpace,
237 impl_vtables.get_slice(subst::FnSpace));
242 /// Translates the adapter that deconstructs a `Box<Trait>` object into
243 /// `Trait` so that a by-value self method can be called.
244 pub fn trans_unboxing_shim(bcx: &Block,
245 llshimmedfn: ValueRef,
247 method_id: ast::DefId,
248 substs: subst::Substs)
250 let _icx = push_ctxt("trans_unboxing_shim");
254 // Transform the self type to `Box<self_type>`.
255 let self_type = *method.fty.sig.inputs.get(0);
256 let boxed_self_type = ty::mk_uniq(tcx, self_type);
257 let boxed_function_type = ty::FnSig {
258 binder_id: method.fty.sig.binder_id,
259 inputs: method.fty.sig.inputs.iter().enumerate().map(|(i, typ)| {
266 output: method.fty.sig.output,
269 let boxed_function_type = ty::BareFnTy {
270 fn_style: method.fty.fn_style,
272 sig: boxed_function_type,
274 let boxed_function_type =
275 ty::mk_bare_fn(tcx, boxed_function_type).subst(tcx, &substs);
277 ty::mk_bare_fn(tcx, method.fty.clone()).subst(tcx, &substs);
279 let function_name = ty::with_path(tcx, method_id, |path| {
280 link::mangle_internal_name_by_path_and_seq(path, "unboxing_shim")
282 let llfn = decl_internal_rust_fn(ccx,
284 function_name.as_slice());
286 let block_arena = TypedArena::new();
287 let empty_param_substs = param_substs::empty();
288 let return_type = ty::ty_fn_ret(boxed_function_type);
289 let fcx = new_fn_ctxt(ccx,
297 let mut bcx = init_function(&fcx, false, return_type);
299 // Create the substituted versions of the self type.
300 let arg_scope = fcx.push_custom_cleanup_scope();
301 let arg_scope_id = cleanup::CustomScope(arg_scope);
302 let boxed_arg_types = ty::ty_fn_args(boxed_function_type);
303 let boxed_self_type = *boxed_arg_types.get(0);
304 let arg_types = ty::ty_fn_args(function_type);
305 let self_type = *arg_types.get(0);
306 let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
308 // Create a datum for self.
309 let llboxedself = unsafe {
310 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(0) as u32)
312 let llboxedself = Datum::new(llboxedself,
317 llboxedself.to_lvalue_datum_in_scope(bcx,
321 // This `Load` is needed because lvalue data are always by-ref.
322 let llboxedself = Load(bcx, boxed_self.val);
324 let llself = if type_is_immediate(ccx, self_type) {
325 let llboxedself = Load(bcx, llboxedself);
326 immediate_rvalue(llboxedself, self_type)
328 let llself = rvalue_scratch_datum(bcx, self_type, "self");
329 memcpy_ty(bcx, llself.val, llboxedself, self_type);
333 // Make sure we don't free the box twice!
334 boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type);
336 // Schedule a cleanup to free the box.
337 fcx.schedule_free_value(arg_scope_id,
339 cleanup::HeapExchange,
342 // Now call the function.
343 let mut llshimmedargs = vec!(llself.val);
344 for i in range(1, arg_types.len()) {
345 llshimmedargs.push(unsafe {
346 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as u32)
349 bcx = trans_call_inner(bcx,
355 data: Fn(llshimmedfn),
358 ArgVals(llshimmedargs.as_slice()),
359 match fcx.llretptr.get() {
361 Some(llretptr) => Some(expr::SaveIn(llretptr)),
364 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
365 finish_fn(&fcx, bcx, return_type);
370 pub fn trans_fn_ref_with_vtables(
372 def_id: ast::DefId, // def id of fn
373 node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
374 substs: subst::Substs, // values for fn's ty params
375 vtables: typeck::vtable_res) // vtables for the call
379 * Translates a reference to a fn/method item, monomorphizing and
380 * inlining as it goes.
384 * - `bcx`: the current block where the reference to the fn occurs
385 * - `def_id`: def id of the fn or method item being referenced
386 * - `node`: node id of the reference to the fn/method, if applicable.
387 * This parameter may be zero; but, if so, the resulting value may not
388 * have the right type, so it must be cast before being used.
389 * - `substs`: values for each of the fn/method's parameters
390 * - `vtables`: values for each bound on each of the type parameters
393 let _icx = push_ctxt("trans_fn_ref_with_vtables");
397 debug!("trans_fn_ref_with_vtables(bcx={}, def_id={}, node={:?}, \
398 substs={}, vtables={})",
405 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
407 // Polytype of the function item (may have type params)
408 let fn_tpt = ty::lookup_item_type(tcx, def_id);
410 // Load the info for the appropriate trait if necessary.
411 match ty::trait_of_method(tcx, def_id) {
414 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
418 // We need to do a bunch of special handling for default methods.
419 // We need to modify the def_id and our substs in order to monomorphize
421 let (is_default, def_id, substs, vtables) =
422 match ty::provided_source(tcx, def_id) {
423 None => (false, def_id, substs, vtables),
425 // There are two relevant substitutions when compiling
426 // default methods. First, there is the substitution for
427 // the type parameters of the impl we are using and the
428 // method we are calling. This substitution is the substs
429 // argument we already have.
430 // In order to compile a default method, though, we need
431 // to consider another substitution: the substitution for
432 // the type parameters on trait; the impl we are using
433 // implements the trait at some particular type
434 // parameters, and we need to substitute for those first.
435 // So, what we need to do is find this substitution and
436 // compose it with the one we already have.
438 let impl_id = ty::method(tcx, def_id).container_id();
439 let method = ty::method(tcx, source_id);
440 let trait_ref = ty::impl_trait_ref(tcx, impl_id)
441 .expect("could not find trait_ref for impl with \
444 // Compute the first substitution
445 let first_subst = make_substs_for_receiver_types(
446 tcx, &*trait_ref, &*method);
449 let new_substs = first_subst.subst(tcx, &substs);
451 debug!("trans_fn_with_vtables - default method: \
452 substs = {}, trait_subst = {}, \
453 first_subst = {}, new_subst = {}, \
455 substs.repr(tcx), trait_ref.substs.repr(tcx),
456 first_subst.repr(tcx), new_substs.repr(tcx),
460 resolve_default_method_vtables(bcx, impl_id, &substs, vtables);
462 debug!("trans_fn_with_vtables - default method: \
464 param_vtables.repr(tcx));
466 (true, source_id, new_substs, param_vtables)
470 // Check whether this fn has an inlined copy and, if so, redirect
471 // def_id to the local id of the inlined copy.
473 if def_id.krate != ast::LOCAL_CRATE {
474 inline::maybe_instantiate_inline(ccx, def_id)
480 // We must monomorphise if the fn has type parameters, is a rust
481 // intrinsic, or is a default method. In particular, if we see an
482 // intrinsic that is inlined from a different crate, we want to reemit the
483 // intrinsic instead of trying to call it in the other crate.
484 let must_monomorphise = if !substs.types.is_empty() || is_default {
486 } else if def_id.krate == ast::LOCAL_CRATE {
487 let map_node = session::expect(
489 tcx.map.find(def_id.node),
490 || "local item should be in ast map".to_string());
493 ast_map::NodeForeignItem(_) => {
494 tcx.map.get_foreign_abi(def_id.node) == synabi::RustIntrinsic
502 // Create a monomorphic version of generic functions
503 if must_monomorphise {
504 // Should be either intra-crate or inlined.
505 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
507 let opt_ref_id = match node {
508 ExprId(id) => if id != 0 { Some(id) } else { None },
509 MethodCall(_) => None,
512 let (val, must_cast) =
513 monomorphize::monomorphic_fn(ccx, def_id, &substs,
514 vtables, opt_ref_id);
516 if must_cast && node != ExprId(0) {
517 // Monotype of the REFERENCE to the function (type params
519 let ref_ty = match node {
520 ExprId(id) => node_id_type(bcx, id),
521 MethodCall(method_call) => {
522 let t = bcx.tcx().method_map.borrow().get(&method_call).ty;
523 monomorphize_type(bcx, t)
528 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
533 // Find the actual function pointer.
535 if def_id.krate == ast::LOCAL_CRATE {
536 // Internal reference.
537 get_item_val(ccx, def_id.node)
539 // External reference.
540 trans_external_path(ccx, def_id, fn_tpt.ty)
544 // This is subtle and surprising, but sometimes we have to bitcast
545 // the resulting fn pointer. The reason has to do with external
546 // functions. If you have two crates that both bind the same C
547 // library, they may not use precisely the same types: for
548 // example, they will probably each declare their own structs,
549 // which are distinct types from LLVM's point of view (nominal
552 // Now, if those two crates are linked into an application, and
553 // they contain inlined code, you can wind up with a situation
554 // where both of those functions wind up being loaded into this
555 // application simultaneously. In that case, the same function
556 // (from LLVM's point of view) requires two types. But of course
557 // LLVM won't allow one function to have two types.
559 // What we currently do, therefore, is declare the function with
560 // one of the two types (whichever happens to come first) and then
561 // bitcast as needed when the function is referenced to make sure
562 // it has the type we expect.
564 // This can occur on either a crate-local or crate-external
565 // reference. It also occurs when testing libcore and in some
566 // other weird situations. Annoying.
567 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
568 let llptrty = llty.ptr_to();
569 if val_ty(val) != llptrty {
570 val = BitCast(bcx, val, llptrty);
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) => (synabi::Rust, 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 // Generate a location to store the result. If the user does
716 // not care about the result, just make a stack slot.
717 let opt_llretslot = match dest {
719 assert!(!type_of::return_uses_outptr(ccx, ret_ty));
722 Some(expr::SaveIn(dst)) => Some(dst),
723 Some(expr::Ignore) => {
724 if !type_is_zero_size(ccx, ret_ty) {
725 Some(alloc_ty(bcx, ret_ty, "__llret"))
727 let llty = type_of::type_of(ccx, ret_ty);
728 Some(C_undef(llty.ptr_to()))
733 let mut llresult = unsafe {
734 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
737 // The code below invokes the function, using either the Rust
738 // conventions (if it is a rust fn) or the native conventions
739 // (otherwise). The important part is that, when all is sad
740 // and done, either the return value of the function will have been
741 // written in opt_llretslot (if it is Some) or `llresult` will be
742 // set appropriately (otherwise).
743 if abi == synabi::Rust {
744 let mut llargs = Vec::new();
746 // Push the out-pointer if we use an out-pointer for this
747 // return type, otherwise push "undef".
748 if type_of::return_uses_outptr(ccx, ret_ty) {
749 llargs.push(opt_llretslot.unwrap());
752 // Push the environment (or a trait object's self).
753 match (llenv, llself) {
754 (Some(llenv), None) => {
757 (None, Some(llself)) => llargs.push(llself),
761 // Push the arguments.
762 bcx = trans_args(bcx, args, callee_ty, &mut llargs,
763 cleanup::CustomScope(arg_cleanup_scope),
766 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
768 // Invoke the actual rust fn and update bcx/llresult.
769 let (llret, b) = base::invoke(bcx,
777 // If the Rust convention for this type is return via
778 // the return value, copy it into llretslot.
779 match opt_llretslot {
781 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
782 !type_is_zero_size(bcx.ccx(), ret_ty)
784 store_ty(bcx, llret, llretslot, ret_ty)
790 // Lang items are the only case where dest is None, and
791 // they are always Rust fns.
792 assert!(dest.is_some());
794 let mut llargs = Vec::new();
795 let arg_tys = match args {
796 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
797 _ => fail!("expected arg exprs.")
799 bcx = trans_args(bcx, args, callee_ty, &mut llargs,
800 cleanup::CustomScope(arg_cleanup_scope), false);
801 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
802 bcx = foreign::trans_native_call(bcx, callee_ty,
803 llfn, opt_llretslot.unwrap(),
804 llargs.as_slice(), arg_tys);
807 // If the caller doesn't care about the result of this fn call,
808 // drop the temporary slot we made.
811 assert!(!type_of::return_uses_outptr(bcx.ccx(), ret_ty));
813 Some(expr::Ignore) => {
814 // drop the value if it is not being saved.
815 bcx = glue::drop_ty(bcx, opt_llretslot.unwrap(), ret_ty);
817 Some(expr::SaveIn(_)) => { }
820 if ty::type_is_bot(ret_ty) {
824 Result::new(bcx, llresult)
827 pub enum CallArgs<'a> {
828 // Supply value of arguments as a list of expressions that must be
829 // translated. This is used in the common case of `foo(bar, qux)`.
830 ArgExprs(&'a [Gc<ast::Expr>]),
832 // Supply value of arguments as a list of LLVM value refs; frequently
833 // used with lang items and so forth, when the argument is an internal
835 ArgVals(&'a [ValueRef]),
837 // For overloaded operators: `(lhs, Option(rhs, rhs_id))`. `lhs`
838 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
839 // the right-hand-side (if any).
840 ArgOverloadedOp(Datum<Expr>, Option<(Datum<Expr>, ast::NodeId)>),
843 pub fn trans_args<'a>(cx: &'a Block<'a>,
846 llargs: &mut Vec<ValueRef> ,
847 arg_cleanup_scope: cleanup::ScopeId,
850 let _icx = push_ctxt("trans_args");
851 let arg_tys = ty::ty_fn_args(fn_ty);
852 let variadic = ty::fn_is_variadic(fn_ty);
856 // First we figure out the caller's view of the types of the arguments.
857 // This will be needed if this is a generic call, because the callee has
858 // to cast her view of the arguments to the caller's view.
860 ArgExprs(arg_exprs) => {
861 let num_formal_args = arg_tys.len();
862 for (i, arg_expr) in arg_exprs.iter().enumerate() {
863 if i == 0 && ignore_self {
866 let arg_ty = if i >= num_formal_args {
868 expr_ty_adjusted(cx, &**arg_expr)
873 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
874 llargs.push(unpack_result!(bcx, {
875 trans_arg_datum(bcx, arg_ty, arg_datum,
881 ArgOverloadedOp(lhs, rhs) => {
884 llargs.push(unpack_result!(bcx, {
885 trans_arg_datum(bcx, *arg_tys.get(0), lhs,
891 Some((rhs, rhs_id)) => {
892 assert_eq!(arg_tys.len(), 2);
894 llargs.push(unpack_result!(bcx, {
895 trans_arg_datum(bcx, *arg_tys.get(1), rhs,
897 DoAutorefArg(rhs_id))
900 None => assert_eq!(arg_tys.len(), 1)
911 pub enum AutorefArg {
913 DoAutorefArg(ast::NodeId)
916 pub fn trans_arg_datum<'a>(
918 formal_arg_ty: ty::t,
919 arg_datum: Datum<Expr>,
920 arg_cleanup_scope: cleanup::ScopeId,
921 autoref_arg: AutorefArg)
923 let _icx = push_ctxt("trans_arg_datum");
927 debug!("trans_arg_datum({})",
928 formal_arg_ty.repr(bcx.tcx()));
930 let arg_datum_ty = arg_datum.ty;
932 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
935 if ty::type_is_bot(arg_datum_ty) {
936 // For values of type _|_, we generate an
937 // "undef" value, as such a value should never
938 // be inspected. It's important for the value
939 // to have type lldestty (the callee's expected type).
940 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
942 val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
945 // FIXME(#3548) use the adjustments table
947 DoAutorefArg(arg_id) => {
948 // We will pass argument by reference
949 // We want an lvalue, so that we can pass by reference and
950 let arg_datum = unpack_datum!(
951 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
955 // Make this an rvalue, since we are going to be
956 // passing ownership.
957 let arg_datum = unpack_datum!(
958 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
960 // Now that arg_datum is owned, get it into the appropriate
961 // mode (ref vs value).
962 let arg_datum = unpack_datum!(
963 bcx, arg_datum.to_appropriate_datum(bcx));
965 // Technically, ownership of val passes to the callee.
966 // However, we must cleanup should we fail before the
967 // callee is actually invoked.
968 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
972 if formal_arg_ty != arg_datum_ty {
973 // this could happen due to e.g. subtyping
974 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
975 debug!("casting actual type ({}) to match formal ({})",
976 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
977 val = PointerCast(bcx, val, llformal_arg_ty);
981 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
982 Result::new(bcx, val)