]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/callee.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[rust.git] / src / librustc_trans / trans / callee.rs
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.
4 //
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.
10
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
15 //! closure.
16
17 pub use self::AutorefArg::*;
18 pub use self::CalleeData::*;
19 pub use self::CallArgs::*;
20
21 use arena::TypedArena;
22 use back::link;
23 use session;
24 use llvm::{ValueRef};
25 use llvm::get_param;
26 use llvm;
27 use metadata::csearch;
28 use middle::def;
29 use middle::subst;
30 use middle::subst::{Subst, Substs};
31 use trans::adt;
32 use trans::base;
33 use trans::base::*;
34 use trans::build::*;
35 use trans::callee;
36 use trans::cleanup;
37 use trans::cleanup::CleanupMethods;
38 use trans::closure;
39 use trans::common::{self, Block, Result, NodeIdAndSpan, ExprId, CrateContext,
40                     ExprOrMethodCall, FunctionContext, MethodCallKey};
41 use trans::consts;
42 use trans::datum::*;
43 use trans::debuginfo::{DebugLoc, ToDebugLoc};
44 use trans::expr;
45 use trans::glue;
46 use trans::inline;
47 use trans::foreign;
48 use trans::intrinsic;
49 use trans::meth;
50 use trans::monomorphize;
51 use trans::type_::Type;
52 use trans::type_of;
53 use middle::ty::{self, Ty};
54 use middle::ty::MethodCall;
55 use util::ppaux::Repr;
56 use util::ppaux::ty_to_string;
57
58 use syntax::abi as synabi;
59 use syntax::ast;
60 use syntax::ast_map;
61 use syntax::ptr::P;
62
63 #[derive(Copy)]
64 pub struct MethodData {
65     pub llfn: ValueRef,
66     pub llself: ValueRef,
67 }
68
69 pub enum CalleeData<'tcx> {
70     // Constructor for enum variant/tuple-like-struct
71     // i.e. Some, Ok
72     NamedTupleConstructor(subst::Substs<'tcx>, ty::Disr),
73
74     // Represents a (possibly monomorphized) top-level fn item or method
75     // item. Note that this is just the fn-ptr and is not a Rust closure
76     // value (which is a pair).
77     Fn(/* llfn */ ValueRef),
78
79     Intrinsic(ast::NodeId, subst::Substs<'tcx>),
80
81     TraitItem(MethodData)
82 }
83
84 pub struct Callee<'blk, 'tcx: 'blk> {
85     pub bcx: Block<'blk, 'tcx>,
86     pub data: CalleeData<'tcx>,
87 }
88
89 fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
90                      -> Callee<'blk, 'tcx> {
91     let _icx = push_ctxt("trans_callee");
92     debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
93
94     // pick out special kinds of expressions that can be called:
95     match expr.node {
96         ast::ExprPath(_) | ast::ExprQPath(_) => {
97             return trans_def(bcx, bcx.def(expr.id), expr);
98         }
99         _ => {}
100     }
101
102     // any other expressions are closures:
103     return datum_callee(bcx, expr);
104
105     fn datum_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
106                                 -> Callee<'blk, 'tcx> {
107         let DatumBlock { bcx, datum, .. } = expr::trans(bcx, expr);
108         match datum.ty.sty {
109             ty::ty_bare_fn(..) => {
110                 let llval = datum.to_llscalarish(bcx);
111                 return Callee {
112                     bcx: bcx,
113                     data: Fn(llval),
114                 };
115             }
116             _ => {
117                 bcx.tcx().sess.span_bug(
118                     expr.span,
119                     &format!("type of callee is neither bare-fn nor closure: \
120                              {}",
121                             bcx.ty_to_string(datum.ty))[]);
122             }
123         }
124     }
125
126     fn fn_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, llfn: ValueRef)
127                              -> Callee<'blk, 'tcx> {
128         return Callee {
129             bcx: bcx,
130             data: Fn(llfn),
131         };
132     }
133
134     fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
135                              def: def::Def,
136                              ref_expr: &ast::Expr)
137                              -> Callee<'blk, 'tcx> {
138         debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
139         let expr_ty = common::node_id_type(bcx, ref_expr.id);
140         match def {
141             def::DefFn(did, _) if {
142                 let maybe_def_id = inline::get_local_instance(bcx.ccx(), did);
143                 let maybe_ast_node = maybe_def_id.and_then(|def_id| bcx.tcx().map
144                                                                              .find(def_id.node));
145                 match maybe_ast_node {
146                     Some(ast_map::NodeStructCtor(_)) => true,
147                     _ => false
148                 }
149             } => {
150                 let substs = common::node_id_substs(bcx.ccx(),
151                                                     ExprId(ref_expr.id),
152                                                     bcx.fcx.param_substs);
153                 Callee {
154                     bcx: bcx,
155                     data: NamedTupleConstructor(substs, 0)
156                 }
157             }
158             def::DefFn(did, _) if match expr_ty.sty {
159                 ty::ty_bare_fn(_, ref f) => f.abi == synabi::RustIntrinsic,
160                 _ => false
161             } => {
162                 let substs = common::node_id_substs(bcx.ccx(),
163                                                     ExprId(ref_expr.id),
164                                                     bcx.fcx.param_substs);
165                 let def_id = inline::maybe_instantiate_inline(bcx.ccx(), did);
166                 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
167             }
168             def::DefFn(did, _) | def::DefMethod(did, _, def::FromImpl(_)) |
169             def::DefStaticMethod(did, def::FromImpl(_)) => {
170                 fn_callee(bcx, trans_fn_ref(bcx.ccx(), did, ExprId(ref_expr.id),
171                                             bcx.fcx.param_substs).val)
172             }
173             def::DefStaticMethod(meth_did, def::FromTrait(trait_did)) |
174             def::DefMethod(meth_did, _, def::FromTrait(trait_did)) => {
175                 fn_callee(bcx, meth::trans_static_method_callee(bcx.ccx(),
176                                                                 meth_did,
177                                                                 trait_did,
178                                                                 ref_expr.id,
179                                                                 bcx.fcx.param_substs).val)
180             }
181             def::DefVariant(tid, vid, _) => {
182                 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
183                 let substs = common::node_id_substs(bcx.ccx(),
184                                                     ExprId(ref_expr.id),
185                                                     bcx.fcx.param_substs);
186
187                 // Nullary variants are not callable
188                 assert!(vinfo.args.len() > 0);
189
190                 Callee {
191                     bcx: bcx,
192                     data: NamedTupleConstructor(substs, vinfo.disr_val)
193                 }
194             }
195             def::DefStruct(_) => {
196                 let substs = common::node_id_substs(bcx.ccx(),
197                                                     ExprId(ref_expr.id),
198                                                     bcx.fcx.param_substs);
199                 Callee {
200                     bcx: bcx,
201                     data: NamedTupleConstructor(substs, 0)
202                 }
203             }
204             def::DefStatic(..) |
205             def::DefConst(..) |
206             def::DefLocal(..) |
207             def::DefUpvar(..) => {
208                 datum_callee(bcx, ref_expr)
209             }
210             def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
211             def::DefTy(..) | def::DefPrimTy(..) | def::DefAssociatedTy(..) |
212             def::DefUse(..) | def::DefTyParamBinder(..) |
213             def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
214             def::DefSelfTy(..) | def::DefAssociatedPath(..) => {
215                 bcx.tcx().sess.span_bug(
216                     ref_expr.span,
217                     &format!("cannot translate def {:?} \
218                              to a callable thing!", def)[]);
219             }
220         }
221     }
222 }
223
224 /// Translates a reference (with id `ref_id`) to the fn/method with id `def_id` into a function
225 /// pointer. This may require monomorphization or inlining.
226 pub fn trans_fn_ref<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
227                               def_id: ast::DefId,
228                               node: ExprOrMethodCall,
229                               param_substs: &'tcx subst::Substs<'tcx>)
230                               -> Datum<'tcx, Rvalue> {
231     let _icx = push_ctxt("trans_fn_ref");
232
233     let substs = common::node_id_substs(ccx, node, param_substs);
234     debug!("trans_fn_ref(def_id={}, node={:?}, substs={})",
235            def_id.repr(ccx.tcx()),
236            node,
237            substs.repr(ccx.tcx()));
238     trans_fn_ref_with_substs(ccx, def_id, node, param_substs, substs)
239 }
240
241 fn trans_fn_ref_with_substs_to_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
242                                                   def_id: ast::DefId,
243                                                   ref_id: ast::NodeId,
244                                                   substs: subst::Substs<'tcx>)
245                                                   -> Callee<'blk, 'tcx> {
246     Callee {
247         bcx: bcx,
248         data: Fn(trans_fn_ref_with_substs(bcx.ccx(),
249                                           def_id,
250                                           ExprId(ref_id),
251                                           bcx.fcx.param_substs,
252                                           substs).val),
253     }
254 }
255
256 /// Translates an adapter that implements the `Fn` trait for a fn
257 /// pointer. This is basically the equivalent of something like:
258 ///
259 /// ```rust
260 /// impl<'a> Fn(&'a int) -> &'a int for fn(&int) -> &int {
261 ///     extern "rust-abi" fn call(&self, args: (&'a int,)) -> &'a int {
262 ///         (*self)(args.0)
263 ///     }
264 /// }
265 /// ```
266 ///
267 /// but for the bare function type given.
268 pub fn trans_fn_pointer_shim<'a, 'tcx>(
269     ccx: &'a CrateContext<'a, 'tcx>,
270     bare_fn_ty: Ty<'tcx>)
271     -> ValueRef
272 {
273     let _icx = push_ctxt("trans_fn_pointer_shim");
274     let tcx = ccx.tcx();
275
276     let bare_fn_ty = common::erase_regions(tcx, &bare_fn_ty);
277     match ccx.fn_pointer_shims().borrow().get(&bare_fn_ty) {
278         Some(&llval) => { return llval; }
279         None => { }
280     }
281
282     debug!("trans_fn_pointer_shim(bare_fn_ty={})",
283            bare_fn_ty.repr(tcx));
284
285     // This is an impl of `Fn` trait, so receiver is `&self`.
286     let bare_fn_ty_ref = ty::mk_imm_rptr(tcx, tcx.mk_region(ty::ReStatic), bare_fn_ty);
287
288     // Construct the "tuply" version of `bare_fn_ty`. It takes two arguments: `self`,
289     // which is the fn pointer, and `args`, which is the arguments tuple.
290     let (opt_def_id, sig) =
291         match bare_fn_ty.sty {
292             ty::ty_bare_fn(opt_def_id,
293                            &ty::BareFnTy { unsafety: ast::Unsafety::Normal,
294                                            abi: synabi::Rust,
295                                            ref sig }) => {
296                 (opt_def_id, sig)
297             }
298
299             _ => {
300                 tcx.sess.bug(&format!("trans_fn_pointer_shim invoked on invalid type: {}",
301                                            bare_fn_ty.repr(tcx))[]);
302             }
303         };
304     let sig = ty::erase_late_bound_regions(tcx, sig);
305     let tuple_input_ty = ty::mk_tup(tcx, sig.inputs.to_vec());
306     let tuple_fn_ty = ty::mk_bare_fn(tcx,
307                                      opt_def_id,
308                                      tcx.mk_bare_fn(ty::BareFnTy {
309                                          unsafety: ast::Unsafety::Normal,
310                                          abi: synabi::RustCall,
311                                          sig: ty::Binder(ty::FnSig {
312                                              inputs: vec![bare_fn_ty_ref,
313                                                           tuple_input_ty],
314                                              output: sig.output,
315                                              variadic: false
316                                          })}));
317     debug!("tuple_fn_ty: {}", tuple_fn_ty.repr(tcx));
318
319     //
320     let function_name =
321         link::mangle_internal_name_by_type_and_seq(ccx, bare_fn_ty,
322                                                    "fn_pointer_shim");
323     let llfn =
324         decl_internal_rust_fn(ccx,
325                               tuple_fn_ty,
326                               &function_name[]);
327
328     //
329     let empty_substs = tcx.mk_substs(Substs::trans_empty());
330     let (block_arena, fcx): (TypedArena<_>, FunctionContext);
331     block_arena = TypedArena::new();
332     fcx = new_fn_ctxt(ccx,
333                       llfn,
334                       ast::DUMMY_NODE_ID,
335                       false,
336                       sig.output,
337                       empty_substs,
338                       None,
339                       &block_arena);
340     let mut bcx = init_function(&fcx, false, sig.output);
341
342     // the first argument (`self`) will be ptr to the the fn pointer
343     let llfnpointer =
344         Load(bcx, get_param(fcx.llfn, fcx.arg_pos(0) as u32));
345
346     // the remaining arguments will be the untupled values
347     let llargs: Vec<_> =
348         sig.inputs.iter()
349         .enumerate()
350         .map(|(i, _)| get_param(fcx.llfn, fcx.arg_pos(i+1) as u32))
351         .collect();
352     assert!(!fcx.needs_ret_allocas);
353
354     let dest = fcx.llretslotptr.get().map(|_|
355         expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot"))
356     );
357
358     bcx = trans_call_inner(bcx,
359                            DebugLoc::None,
360                            bare_fn_ty,
361                            |bcx, _| Callee { bcx: bcx, data: Fn(llfnpointer) },
362                            ArgVals(&llargs[]),
363                            dest).bcx;
364
365     finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
366
367     ccx.fn_pointer_shims().borrow_mut().insert(bare_fn_ty, llfn);
368
369     llfn
370 }
371
372 /// Translates a reference to a fn/method item, monomorphizing and
373 /// inlining as it goes.
374 ///
375 /// # Parameters
376 ///
377 /// - `ccx`: the crate context
378 /// - `def_id`: def id of the fn or method item being referenced
379 /// - `node`: node id of the reference to the fn/method, if applicable.
380 ///   This parameter may be zero; but, if so, the resulting value may not
381 ///   have the right type, so it must be cast before being used.
382 /// - `param_substs`: if the `node` is in a polymorphic function, these
383 ///   are the substitutions required to monomorphize its type
384 /// - `substs`: values for each of the fn/method's parameters
385 pub fn trans_fn_ref_with_substs<'a, 'tcx>(
386     ccx: &CrateContext<'a, 'tcx>,
387     def_id: ast::DefId,
388     node: ExprOrMethodCall,
389     param_substs: &'tcx subst::Substs<'tcx>,
390     substs: subst::Substs<'tcx>)
391     -> Datum<'tcx, Rvalue>
392 {
393     let _icx = push_ctxt("trans_fn_ref_with_substs");
394     let tcx = ccx.tcx();
395
396     debug!("trans_fn_ref_with_substs(def_id={}, node={:?}, \
397             param_substs={}, substs={})",
398            def_id.repr(tcx),
399            node,
400            param_substs.repr(tcx),
401            substs.repr(tcx));
402
403     assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
404     assert!(substs.types.all(|t| !ty::type_has_escaping_regions(*t)));
405     let substs = substs.erase_regions();
406
407     // Load the info for the appropriate trait if necessary.
408     match ty::trait_of_item(tcx, def_id) {
409         None => {}
410         Some(trait_id) => {
411             ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
412         }
413     }
414
415     // We need to do a bunch of special handling for default methods.
416     // We need to modify the def_id and our substs in order to monomorphize
417     // the function.
418     let (is_default, def_id, substs) = match ty::provided_source(tcx, def_id) {
419         None => {
420             (false, def_id, tcx.mk_substs(substs))
421         }
422         Some(source_id) => {
423             // There are two relevant substitutions when compiling
424             // default methods. First, there is the substitution for
425             // the type parameters of the impl we are using and the
426             // method we are calling. This substitution is the substs
427             // argument we already have.
428             // In order to compile a default method, though, we need
429             // to consider another substitution: the substitution for
430             // the type parameters on trait; the impl we are using
431             // implements the trait at some particular type
432             // parameters, and we need to substitute for those first.
433             // So, what we need to do is find this substitution and
434             // compose it with the one we already have.
435
436             let impl_id = ty::impl_or_trait_item(tcx, def_id).container()
437                                                              .id();
438             let impl_or_trait_item = ty::impl_or_trait_item(tcx, source_id);
439             match impl_or_trait_item {
440                 ty::MethodTraitItem(method) => {
441                     let trait_ref = ty::impl_trait_ref(tcx, impl_id).unwrap();
442
443                     // Compute the first substitution
444                     let first_subst =
445                         ty::make_substs_for_receiver_types(tcx, &*trait_ref, &*method)
446                         .erase_regions();
447
448                     // And compose them
449                     let new_substs = tcx.mk_substs(first_subst.subst(tcx, &substs));
450
451                     debug!("trans_fn_with_vtables - default method: \
452                             substs = {}, trait_subst = {}, \
453                             first_subst = {}, new_subst = {}",
454                            substs.repr(tcx), trait_ref.substs.repr(tcx),
455                            first_subst.repr(tcx), new_substs.repr(tcx));
456
457                     (true, source_id, new_substs)
458                 }
459                 ty::TypeTraitItem(_) => {
460                     tcx.sess.bug("trans_fn_ref_with_vtables() tried \
461                                   to translate an associated type?!")
462                 }
463             }
464         }
465     };
466
467     // If this is a closure, redirect to it.
468     match closure::get_or_create_declaration_if_closure(ccx, def_id, substs) {
469         None => {}
470         Some(llfn) => return llfn,
471     }
472
473     // Check whether this fn has an inlined copy and, if so, redirect
474     // def_id to the local id of the inlined copy.
475     let def_id = inline::maybe_instantiate_inline(ccx, def_id);
476
477     // We must monomorphise if the fn has type parameters, is a default method,
478     // or is a named tuple constructor.
479     let must_monomorphise = if !substs.types.is_empty() || is_default {
480         true
481     } else if def_id.krate == ast::LOCAL_CRATE {
482         let map_node = session::expect(
483             ccx.sess(),
484             tcx.map.find(def_id.node),
485             || "local item should be in ast map".to_string());
486
487         match map_node {
488             ast_map::NodeVariant(v) => match v.node.kind {
489                 ast::TupleVariantKind(ref args) => args.len() > 0,
490                 _ => false
491             },
492             ast_map::NodeStructCtor(_) => true,
493             _ => false
494         }
495     } else {
496         false
497     };
498
499     // Create a monomorphic version of generic functions
500     if must_monomorphise {
501         // Should be either intra-crate or inlined.
502         assert_eq!(def_id.krate, ast::LOCAL_CRATE);
503
504         let opt_ref_id = match node {
505             ExprId(id) => if id != 0 { Some(id) } else { None },
506             MethodCallKey(_) => None,
507         };
508
509         let (val, fn_ty, must_cast) =
510             monomorphize::monomorphic_fn(ccx, def_id, substs, opt_ref_id);
511         if must_cast && node != ExprId(0) {
512             // Monotype of the REFERENCE to the function (type params
513             // are subst'd)
514             let ref_ty = match node {
515                 ExprId(id) => ty::node_id_to_type(tcx, id),
516                 MethodCallKey(method_call) => {
517                     (*tcx.method_map.borrow())[method_call].ty
518                 }
519             };
520             let ref_ty = monomorphize::apply_param_substs(tcx,
521                                                           param_substs,
522                                                           &ref_ty);
523             let llptrty = type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to();
524             if llptrty != common::val_ty(val) {
525                 let val = consts::ptrcast(val, llptrty);
526                 return Datum::new(val, ref_ty, Rvalue::new(ByValue));
527             }
528         }
529         return Datum::new(val, fn_ty, Rvalue::new(ByValue));
530     }
531
532     // Type scheme of the function item (may have type params)
533     let fn_type_scheme = ty::lookup_item_type(tcx, def_id);
534     let fn_type = monomorphize::normalize_associated_type(tcx, &fn_type_scheme.ty);
535
536     // Find the actual function pointer.
537     let mut val = {
538         if def_id.krate == ast::LOCAL_CRATE {
539             // Internal reference.
540             get_item_val(ccx, def_id.node)
541         } else {
542             // External reference.
543             trans_external_path(ccx, def_id, fn_type)
544         }
545     };
546
547     // This is subtle and surprising, but sometimes we have to bitcast
548     // the resulting fn pointer.  The reason has to do with external
549     // functions.  If you have two crates that both bind the same C
550     // library, they may not use precisely the same types: for
551     // example, they will probably each declare their own structs,
552     // which are distinct types from LLVM's point of view (nominal
553     // types).
554     //
555     // Now, if those two crates are linked into an application, and
556     // they contain inlined code, you can wind up with a situation
557     // where both of those functions wind up being loaded into this
558     // application simultaneously. In that case, the same function
559     // (from LLVM's point of view) requires two types. But of course
560     // LLVM won't allow one function to have two types.
561     //
562     // What we currently do, therefore, is declare the function with
563     // one of the two types (whichever happens to come first) and then
564     // bitcast as needed when the function is referenced to make sure
565     // it has the type we expect.
566     //
567     // This can occur on either a crate-local or crate-external
568     // reference. It also occurs when testing libcore and in some
569     // other weird situations. Annoying.
570     let llty = type_of::type_of_fn_from_ty(ccx, fn_type);
571     let llptrty = llty.ptr_to();
572     if common::val_ty(val) != llptrty {
573         debug!("trans_fn_ref_with_vtables(): casting pointer!");
574         val = consts::ptrcast(val, llptrty);
575     } else {
576         debug!("trans_fn_ref_with_vtables(): not casting pointer!");
577     }
578
579     Datum::new(val, fn_type, Rvalue::new(ByValue))
580 }
581
582 // ______________________________________________________________________
583 // Translating calls
584
585 pub fn trans_call<'a, 'blk, 'tcx>(in_cx: Block<'blk, 'tcx>,
586                                   call_expr: &ast::Expr,
587                                   f: &ast::Expr,
588                                   args: CallArgs<'a, 'tcx>,
589                                   dest: expr::Dest)
590                                   -> Block<'blk, 'tcx> {
591     let _icx = push_ctxt("trans_call");
592     trans_call_inner(in_cx,
593                      call_expr.debug_loc(),
594                      common::expr_ty_adjusted(in_cx, f),
595                      |cx, _| trans(cx, f),
596                      args,
597                      Some(dest)).bcx
598 }
599
600 pub fn trans_method_call<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
601                                          call_expr: &ast::Expr,
602                                          rcvr: &ast::Expr,
603                                          args: CallArgs<'a, 'tcx>,
604                                          dest: expr::Dest)
605                                          -> Block<'blk, 'tcx> {
606     let _icx = push_ctxt("trans_method_call");
607     debug!("trans_method_call(call_expr={})", call_expr.repr(bcx.tcx()));
608     let method_call = MethodCall::expr(call_expr.id);
609     let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
610     trans_call_inner(
611         bcx,
612         call_expr.debug_loc(),
613         common::monomorphize_type(bcx, method_ty),
614         |cx, arg_cleanup_scope| {
615             meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
616         },
617         args,
618         Some(dest)).bcx
619 }
620
621 pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
622                                    did: ast::DefId,
623                                    args: &[ValueRef],
624                                    dest: Option<expr::Dest>,
625                                    debug_loc: DebugLoc)
626                                    -> Result<'blk, 'tcx> {
627     let fty = if did.krate == ast::LOCAL_CRATE {
628         ty::node_id_to_type(bcx.tcx(), did.node)
629     } else {
630         csearch::get_type(bcx.tcx(), did).ty
631     };
632     callee::trans_call_inner(bcx,
633                              debug_loc,
634                              fty,
635                              |bcx, _| {
636                                 trans_fn_ref_with_substs_to_callee(bcx,
637                                                                    did,
638                                                                    0,
639                                                                    subst::Substs::trans_empty())
640                              },
641                              ArgVals(args),
642                              dest)
643 }
644
645 /// This behemoth of a function translates function calls. Unfortunately, in order to generate more
646 /// efficient LLVM output at -O0, it has quite a complex signature (refactoring this into two
647 /// functions seems like a good idea).
648 ///
649 /// In particular, for lang items, it is invoked with a dest of None, and in that case the return
650 /// value contains the result of the fn. The lang item must not return a structural type or else
651 /// all heck breaks loose.
652 ///
653 /// For non-lang items, `dest` is always Some, and hence the result is written into memory
654 /// somewhere. Nonetheless we return the actual return value of the function.
655 pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
656                                            debug_loc: DebugLoc,
657                                            callee_ty: Ty<'tcx>,
658                                            get_callee: F,
659                                            args: CallArgs<'a, 'tcx>,
660                                            dest: Option<expr::Dest>)
661                                            -> Result<'blk, 'tcx> where
662     F: FnOnce(Block<'blk, 'tcx>, cleanup::ScopeId) -> Callee<'blk, 'tcx>,
663 {
664     // Introduce a temporary cleanup scope that will contain cleanups
665     // for the arguments while they are being evaluated. The purpose
666     // this cleanup is to ensure that, should a panic occur while
667     // evaluating argument N, the values for arguments 0...N-1 are all
668     // cleaned up. If no panic occurs, the values are handed off to
669     // the callee, and hence none of the cleanups in this temporary
670     // scope will ever execute.
671     let fcx = bcx.fcx;
672     let ccx = fcx.ccx;
673     let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
674
675     let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
676     let mut bcx = callee.bcx;
677
678     let (abi, ret_ty) = match callee_ty.sty {
679         ty::ty_bare_fn(_, ref f) => {
680             let output = ty::erase_late_bound_regions(bcx.tcx(), &f.sig.output());
681             (f.abi, output)
682         }
683         _ => panic!("expected bare rust fn or closure in trans_call_inner")
684     };
685
686     let (llfn, llenv, llself) = match callee.data {
687         Fn(llfn) => {
688             (llfn, None, None)
689         }
690         TraitItem(d) => {
691             (d.llfn, None, Some(d.llself))
692         }
693         Intrinsic(node, substs) => {
694             assert!(abi == synabi::RustIntrinsic);
695             assert!(dest.is_some());
696
697             let call_info = match debug_loc {
698                 DebugLoc::At(id, span) => NodeIdAndSpan { id: id, span: span },
699                 DebugLoc::None => {
700                     bcx.sess().bug("No call info for intrinsic call?")
701                 }
702             };
703
704             return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
705                                                    arg_cleanup_scope, args,
706                                                    dest.unwrap(), substs,
707                                                    call_info);
708         }
709         NamedTupleConstructor(substs, disr) => {
710             assert!(dest.is_some());
711             fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
712
713             let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
714             return base::trans_named_tuple_constructor(bcx,
715                                                        ctor_ty,
716                                                        disr,
717                                                        args,
718                                                        dest.unwrap(),
719                                                        debug_loc);
720         }
721     };
722
723     // Intrinsics should not become actual functions.
724     // We trans them in place in `trans_intrinsic_call`
725     assert!(abi != synabi::RustIntrinsic);
726
727     let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
728
729     // Generate a location to store the result. If the user does
730     // not care about the result, just make a stack slot.
731     let opt_llretslot = dest.and_then(|dest| match dest {
732         expr::SaveIn(dst) => Some(dst),
733         expr::Ignore => {
734             let ret_ty = match ret_ty {
735                 ty::FnConverging(ret_ty) => ret_ty,
736                 ty::FnDiverging => ty::mk_nil(ccx.tcx())
737             };
738             if !is_rust_fn ||
739               type_of::return_uses_outptr(ccx, ret_ty) ||
740               common::type_needs_drop(bcx.tcx(), ret_ty) {
741                 // Push the out-pointer if we use an out-pointer for this
742                 // return type, otherwise push "undef".
743                 if common::type_is_zero_size(ccx, ret_ty) {
744                     let llty = type_of::type_of(ccx, ret_ty);
745                     Some(common::C_undef(llty.ptr_to()))
746                 } else {
747                     Some(alloc_ty(bcx, ret_ty, "__llret"))
748                 }
749             } else {
750                 None
751             }
752         }
753     });
754
755     let mut llresult = unsafe {
756         llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
757     };
758
759     // The code below invokes the function, using either the Rust
760     // conventions (if it is a rust fn) or the native conventions
761     // (otherwise).  The important part is that, when all is said
762     // and done, either the return value of the function will have been
763     // written in opt_llretslot (if it is Some) or `llresult` will be
764     // set appropriately (otherwise).
765     if is_rust_fn {
766         let mut llargs = Vec::new();
767
768         if let (ty::FnConverging(ret_ty), Some(llretslot)) = (ret_ty, opt_llretslot) {
769             if type_of::return_uses_outptr(ccx, ret_ty) {
770                 llargs.push(llretslot);
771             }
772         }
773
774         // Push the environment (or a trait object's self).
775         match (llenv, llself) {
776             (Some(llenv), None) => llargs.push(llenv),
777             (None, Some(llself)) => llargs.push(llself),
778             _ => {}
779         }
780
781         // Push the arguments.
782         bcx = trans_args(bcx,
783                          args,
784                          callee_ty,
785                          &mut llargs,
786                          cleanup::CustomScope(arg_cleanup_scope),
787                          llself.is_some(),
788                          abi);
789
790         fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
791
792         // Invoke the actual rust fn and update bcx/llresult.
793         let (llret, b) = base::invoke(bcx,
794                                       llfn,
795                                       &llargs[],
796                                       callee_ty,
797                                       debug_loc);
798         bcx = b;
799         llresult = llret;
800
801         // If the Rust convention for this type is return via
802         // the return value, copy it into llretslot.
803         match (opt_llretslot, ret_ty) {
804             (Some(llretslot), ty::FnConverging(ret_ty)) => {
805                 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
806                     !common::type_is_zero_size(bcx.ccx(), ret_ty)
807                 {
808                     store_ty(bcx, llret, llretslot, ret_ty)
809                 }
810             }
811             (_, _) => {}
812         }
813     } else {
814         // Lang items are the only case where dest is None, and
815         // they are always Rust fns.
816         assert!(dest.is_some());
817
818         let mut llargs = Vec::new();
819         let arg_tys = match args {
820             ArgExprs(a) => a.iter().map(|x| common::expr_ty(bcx, &**x)).collect(),
821             _ => panic!("expected arg exprs.")
822         };
823         bcx = trans_args(bcx,
824                          args,
825                          callee_ty,
826                          &mut llargs,
827                          cleanup::CustomScope(arg_cleanup_scope),
828                          false,
829                          abi);
830         fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
831
832         bcx = foreign::trans_native_call(bcx,
833                                          callee_ty,
834                                          llfn,
835                                          opt_llretslot.unwrap(),
836                                          &llargs[],
837                                          arg_tys,
838                                          debug_loc);
839     }
840
841     fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_cleanup_scope);
842
843     // If the caller doesn't care about the result of this fn call,
844     // drop the temporary slot we made.
845     match (dest, opt_llretslot, ret_ty) {
846         (Some(expr::Ignore), Some(llretslot), ty::FnConverging(ret_ty)) => {
847             // drop the value if it is not being saved.
848             bcx = glue::drop_ty(bcx,
849                                 llretslot,
850                                 ret_ty,
851                                 debug_loc);
852             call_lifetime_end(bcx, llretslot);
853         }
854         _ => {}
855     }
856
857     if ret_ty == ty::FnDiverging {
858         Unreachable(bcx);
859     }
860
861     Result::new(bcx, llresult)
862 }
863
864 pub enum CallArgs<'a, 'tcx> {
865     // Supply value of arguments as a list of expressions that must be
866     // translated. This is used in the common case of `foo(bar, qux)`.
867     ArgExprs(&'a [P<ast::Expr>]),
868
869     // Supply value of arguments as a list of LLVM value refs; frequently
870     // used with lang items and so forth, when the argument is an internal
871     // value.
872     ArgVals(&'a [ValueRef]),
873
874     // For overloaded operators: `(lhs, Vec(rhs, rhs_id), autoref)`. `lhs`
875     // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
876     // the right-hand-side arguments (if any). `autoref` indicates whether the `rhs`
877     // arguments should be auto-referenced
878     ArgOverloadedOp(Datum<'tcx, Expr>, Vec<(Datum<'tcx, Expr>, ast::NodeId)>, bool),
879
880     // Supply value of arguments as a list of expressions that must be
881     // translated, for overloaded call operators.
882     ArgOverloadedCall(Vec<&'a ast::Expr>),
883 }
884
885 fn trans_args_under_call_abi<'blk, 'tcx>(
886                              mut bcx: Block<'blk, 'tcx>,
887                              arg_exprs: &[P<ast::Expr>],
888                              fn_ty: Ty<'tcx>,
889                              llargs: &mut Vec<ValueRef>,
890                              arg_cleanup_scope: cleanup::ScopeId,
891                              ignore_self: bool)
892                              -> Block<'blk, 'tcx>
893 {
894     let args =
895         ty::erase_late_bound_regions(
896             bcx.tcx(), &ty::ty_fn_args(fn_ty));
897
898     // Translate the `self` argument first.
899     if !ignore_self {
900         let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
901         llargs.push(unpack_result!(bcx, {
902             trans_arg_datum(bcx,
903                             args[0],
904                             arg_datum,
905                             arg_cleanup_scope,
906                             DontAutorefArg)
907         }))
908     }
909
910     // Now untuple the rest of the arguments.
911     let tuple_expr = &arg_exprs[1];
912     let tuple_type = common::node_id_type(bcx, tuple_expr.id);
913
914     match tuple_type.sty {
915         ty::ty_tup(ref field_types) => {
916             let tuple_datum = unpack_datum!(bcx,
917                                             expr::trans(bcx, &**tuple_expr));
918             let tuple_lvalue_datum =
919                 unpack_datum!(bcx,
920                               tuple_datum.to_lvalue_datum(bcx,
921                                                           "args",
922                                                           tuple_expr.id));
923             let repr = adt::represent_type(bcx.ccx(), tuple_type);
924             let repr_ptr = &*repr;
925             for i in 0..field_types.len() {
926                 let arg_datum = tuple_lvalue_datum.get_element(
927                     bcx,
928                     field_types[i],
929                     |srcval| {
930                         adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
931                     });
932                 let arg_datum = arg_datum.to_expr_datum();
933                 let arg_datum =
934                     unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
935                 let arg_datum =
936                     unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
937                 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
938             }
939         }
940         _ => {
941             bcx.sess().span_bug(tuple_expr.span,
942                                 "argument to `.call()` wasn't a tuple?!")
943         }
944     };
945
946     bcx
947 }
948
949 fn trans_overloaded_call_args<'blk, 'tcx>(
950                               mut bcx: Block<'blk, 'tcx>,
951                               arg_exprs: Vec<&ast::Expr>,
952                               fn_ty: Ty<'tcx>,
953                               llargs: &mut Vec<ValueRef>,
954                               arg_cleanup_scope: cleanup::ScopeId,
955                               ignore_self: bool)
956                               -> Block<'blk, 'tcx> {
957     // Translate the `self` argument first.
958     let arg_tys = ty::erase_late_bound_regions(bcx.tcx(),  &ty::ty_fn_args(fn_ty));
959     if !ignore_self {
960         let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
961         llargs.push(unpack_result!(bcx, {
962             trans_arg_datum(bcx,
963                             arg_tys[0],
964                             arg_datum,
965                             arg_cleanup_scope,
966                             DontAutorefArg)
967         }))
968     }
969
970     // Now untuple the rest of the arguments.
971     let tuple_type = arg_tys[1];
972     match tuple_type.sty {
973         ty::ty_tup(ref field_types) => {
974             for (i, &field_type) in field_types.iter().enumerate() {
975                 let arg_datum =
976                     unpack_datum!(bcx, expr::trans(bcx, arg_exprs[i + 1]));
977                 llargs.push(unpack_result!(bcx, {
978                     trans_arg_datum(bcx,
979                                     field_type,
980                                     arg_datum,
981                                     arg_cleanup_scope,
982                                     DontAutorefArg)
983                 }))
984             }
985         }
986         _ => {
987             bcx.sess().span_bug(arg_exprs[0].span,
988                                 "argument to `.call()` wasn't a tuple?!")
989         }
990     };
991
992     bcx
993 }
994
995 pub fn trans_args<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
996                                   args: CallArgs<'a, 'tcx>,
997                                   fn_ty: Ty<'tcx>,
998                                   llargs: &mut Vec<ValueRef>,
999                                   arg_cleanup_scope: cleanup::ScopeId,
1000                                   ignore_self: bool,
1001                                   abi: synabi::Abi)
1002                                   -> Block<'blk, 'tcx> {
1003     debug!("trans_args(abi={})", abi);
1004
1005     let _icx = push_ctxt("trans_args");
1006     let arg_tys = ty::erase_late_bound_regions(cx.tcx(), &ty::ty_fn_args(fn_ty));
1007     let variadic = ty::fn_is_variadic(fn_ty);
1008
1009     let mut bcx = cx;
1010
1011     // First we figure out the caller's view of the types of the arguments.
1012     // This will be needed if this is a generic call, because the callee has
1013     // to cast her view of the arguments to the caller's view.
1014     match args {
1015         ArgExprs(arg_exprs) => {
1016             if abi == synabi::RustCall {
1017                 // This is only used for direct calls to the `call`,
1018                 // `call_mut` or `call_once` functions.
1019                 return trans_args_under_call_abi(cx,
1020                                                  arg_exprs,
1021                                                  fn_ty,
1022                                                  llargs,
1023                                                  arg_cleanup_scope,
1024                                                  ignore_self)
1025             }
1026
1027             let num_formal_args = arg_tys.len();
1028             for (i, arg_expr) in arg_exprs.iter().enumerate() {
1029                 if i == 0 && ignore_self {
1030                     continue;
1031                 }
1032                 let arg_ty = if i >= num_formal_args {
1033                     assert!(variadic);
1034                     common::expr_ty_adjusted(cx, &**arg_expr)
1035                 } else {
1036                     arg_tys[i]
1037                 };
1038
1039                 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1040                 llargs.push(unpack_result!(bcx, {
1041                     trans_arg_datum(bcx, arg_ty, arg_datum,
1042                                     arg_cleanup_scope,
1043                                     DontAutorefArg)
1044                 }));
1045             }
1046         }
1047         ArgOverloadedCall(arg_exprs) => {
1048             return trans_overloaded_call_args(cx,
1049                                               arg_exprs,
1050                                               fn_ty,
1051                                               llargs,
1052                                               arg_cleanup_scope,
1053                                               ignore_self)
1054         }
1055         ArgOverloadedOp(lhs, rhs, autoref) => {
1056             assert!(!variadic);
1057
1058             llargs.push(unpack_result!(bcx, {
1059                 trans_arg_datum(bcx, arg_tys[0], lhs,
1060                                 arg_cleanup_scope,
1061                                 DontAutorefArg)
1062             }));
1063
1064             assert_eq!(arg_tys.len(), 1 + rhs.len());
1065             for (rhs, rhs_id) in rhs {
1066                 llargs.push(unpack_result!(bcx, {
1067                     trans_arg_datum(bcx, arg_tys[1], rhs,
1068                                     arg_cleanup_scope,
1069                                     if autoref { DoAutorefArg(rhs_id) } else { DontAutorefArg })
1070                 }));
1071             }
1072         }
1073         ArgVals(vs) => {
1074             llargs.push_all(vs);
1075         }
1076     }
1077
1078     bcx
1079 }
1080
1081 #[derive(Copy)]
1082 pub enum AutorefArg {
1083     DontAutorefArg,
1084     DoAutorefArg(ast::NodeId)
1085 }
1086
1087 pub fn trans_arg_datum<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1088                                    formal_arg_ty: Ty<'tcx>,
1089                                    arg_datum: Datum<'tcx, Expr>,
1090                                    arg_cleanup_scope: cleanup::ScopeId,
1091                                    autoref_arg: AutorefArg)
1092                                    -> Result<'blk, 'tcx> {
1093     let _icx = push_ctxt("trans_arg_datum");
1094     let mut bcx = bcx;
1095     let ccx = bcx.ccx();
1096
1097     debug!("trans_arg_datum({})",
1098            formal_arg_ty.repr(bcx.tcx()));
1099
1100     let arg_datum_ty = arg_datum.ty;
1101
1102     debug!("   arg datum: {}", arg_datum.to_string(bcx.ccx()));
1103
1104     let mut val;
1105     // FIXME(#3548) use the adjustments table
1106     match autoref_arg {
1107         DoAutorefArg(arg_id) => {
1108             // We will pass argument by reference
1109             // We want an lvalue, so that we can pass by reference and
1110             let arg_datum = unpack_datum!(
1111                 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1112             val = arg_datum.val;
1113         }
1114         DontAutorefArg => {
1115             // Make this an rvalue, since we are going to be
1116             // passing ownership.
1117             let arg_datum = unpack_datum!(
1118                 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1119
1120             // Now that arg_datum is owned, get it into the appropriate
1121             // mode (ref vs value).
1122             let arg_datum = unpack_datum!(
1123                 bcx, arg_datum.to_appropriate_datum(bcx));
1124
1125             // Technically, ownership of val passes to the callee.
1126             // However, we must cleanup should we panic before the
1127             // callee is actually invoked.
1128             val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1129         }
1130     }
1131
1132     if formal_arg_ty != arg_datum_ty {
1133         // this could happen due to e.g. subtyping
1134         let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1135         debug!("casting actual type ({}) to match formal ({})",
1136                bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1137         debug!("Rust types: {}; {}", ty_to_string(bcx.tcx(), arg_datum_ty),
1138                                      ty_to_string(bcx.tcx(), formal_arg_ty));
1139         val = PointerCast(bcx, val, llformal_arg_ty);
1140     }
1141
1142     debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1143     Result::new(bcx, val)
1144 }