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