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