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