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