]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/callee.rs
auto merge of #8594 : bytewiseand/rust/static-fn-ptr, r=pcwalton
[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 std::vec;
20
21 use back::abi;
22 use driver::session;
23 use lib::llvm::ValueRef;
24 use lib::llvm::llvm;
25 use metadata::csearch;
26 use middle::trans::base;
27 use middle::trans::base::*;
28 use middle::trans::build::*;
29 use middle::trans::callee;
30 use middle::trans::common;
31 use middle::trans::common::*;
32 use middle::trans::datum::*;
33 use middle::trans::datum::Datum;
34 use middle::trans::expr;
35 use middle::trans::glue;
36 use middle::trans::inline;
37 use middle::trans::meth;
38 use middle::trans::monomorphize;
39 use middle::trans::type_of;
40 use middle::trans::foreign;
41 use middle::ty;
42 use middle::subst::Subst;
43 use middle::typeck;
44 use middle::typeck::coherence::make_substs_for_receiver_types;
45 use util::ppaux::Repr;
46
47 use middle::trans::type_::Type;
48
49 use syntax::ast;
50 use syntax::abi::AbiSet;
51 use syntax::ast_map;
52 use syntax::visit;
53 use syntax::visit::Visitor;
54
55 // Represents a (possibly monomorphized) top-level fn item or method
56 // item.  Note that this is just the fn-ptr and is not a Rust closure
57 // value (which is a pair).
58 pub struct FnData {
59     llfn: ValueRef,
60 }
61
62 pub struct MethodData {
63     llfn: ValueRef,
64     llself: ValueRef,
65     temp_cleanup: Option<ValueRef>,
66     self_mode: ty::SelfMode,
67 }
68
69 pub enum CalleeData {
70     Closure(Datum),
71     Fn(FnData),
72     Method(MethodData)
73 }
74
75 pub struct Callee {
76     bcx: @mut Block,
77     data: CalleeData
78 }
79
80 pub fn trans(bcx: @mut Block, expr: @ast::expr) -> Callee {
81     let _icx = push_ctxt("trans_callee");
82     debug!("callee::trans(expr=%s)", expr.repr(bcx.tcx()));
83
84     // pick out special kinds of expressions that can be called:
85     match expr.node {
86         ast::expr_path(_) => {
87             return trans_def(bcx, bcx.def(expr.id), expr);
88         }
89         _ => {}
90     }
91
92     // any other expressions are closures:
93     return datum_callee(bcx, expr);
94
95     fn datum_callee(bcx: @mut Block, expr: @ast::expr) -> Callee {
96         let DatumBlock {bcx, datum} = expr::trans_to_datum(bcx, expr);
97         match ty::get(datum.ty).sty {
98             ty::ty_bare_fn(*) => {
99                 let llval = datum.to_appropriate_llval(bcx);
100                 return Callee {bcx: bcx, data: Fn(FnData {llfn: llval})};
101             }
102             ty::ty_closure(*) => {
103                 return Callee {bcx: bcx, data: Closure(datum)};
104             }
105             _ => {
106                 bcx.tcx().sess.span_bug(
107                     expr.span,
108                     fmt!("Type of callee is neither bare-fn nor closure: %s",
109                          bcx.ty_to_str(datum.ty)));
110             }
111         }
112     }
113
114     fn fn_callee(bcx: @mut Block, fd: FnData) -> Callee {
115         return Callee {bcx: bcx, data: Fn(fd)};
116     }
117
118     fn trans_def(bcx: @mut Block, def: ast::def, ref_expr: @ast::expr) -> Callee {
119         match def {
120             ast::def_fn(did, _) | ast::def_static_method(did, None, _) => {
121                 fn_callee(bcx, trans_fn_ref(bcx, did, ref_expr.id))
122             }
123             ast::def_static_method(impl_did, Some(trait_did), _) => {
124                 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
125                                                                 trait_did,
126                                                                 ref_expr.id))
127             }
128             ast::def_variant(tid, vid) => {
129                 // nullary variants are not callable
130                 assert!(ty::enum_variant_with_id(bcx.tcx(),
131                                                       tid,
132                                                       vid).args.len() > 0u);
133                 fn_callee(bcx, trans_fn_ref(bcx, vid, ref_expr.id))
134             }
135             ast::def_struct(def_id) => {
136                 fn_callee(bcx, trans_fn_ref(bcx, def_id, ref_expr.id))
137             }
138             ast::def_static(*) |
139             ast::def_arg(*) |
140             ast::def_local(*) |
141             ast::def_binding(*) |
142             ast::def_upvar(*) |
143             ast::def_self(*) => {
144                 datum_callee(bcx, ref_expr)
145             }
146             ast::def_mod(*) | ast::def_foreign_mod(*) | ast::def_trait(*) |
147             ast::def_ty(*) | ast::def_prim_ty(*) |
148             ast::def_use(*) | ast::def_typaram_binder(*) |
149             ast::def_region(*) | ast::def_label(*) | ast::def_ty_param(*) |
150             ast::def_self_ty(*) | ast::def_method(*) => {
151                 bcx.tcx().sess.span_bug(
152                     ref_expr.span,
153                     fmt!("Cannot translate def %? \
154                           to a callable thing!", def));
155             }
156         }
157     }
158 }
159
160 pub fn trans_fn_ref_to_callee(bcx: @mut Block,
161                               def_id: ast::def_id,
162                               ref_id: ast::NodeId) -> Callee {
163     Callee {bcx: bcx,
164             data: Fn(trans_fn_ref(bcx, def_id, ref_id))}
165 }
166
167 pub fn trans_fn_ref(bcx: @mut Block,
168                     def_id: ast::def_id,
169                     ref_id: ast::NodeId) -> FnData {
170     /*!
171      *
172      * Translates a reference (with id `ref_id`) to the fn/method
173      * with id `def_id` into a function pointer.  This may require
174      * monomorphization or inlining. */
175
176     let _icx = push_ctxt("trans_fn_ref");
177
178     let type_params = node_id_type_params(bcx, ref_id);
179     let vtables = node_vtables(bcx, ref_id);
180     debug!("trans_fn_ref(def_id=%s, ref_id=%?, type_params=%s, vtables=%s)",
181            def_id.repr(bcx.tcx()), ref_id, type_params.repr(bcx.tcx()),
182            vtables.repr(bcx.tcx()));
183     trans_fn_ref_with_vtables(bcx, def_id, ref_id, type_params, vtables)
184 }
185
186 pub fn trans_fn_ref_with_vtables_to_callee(
187         bcx: @mut Block,
188         def_id: ast::def_id,
189         ref_id: ast::NodeId,
190         type_params: &[ty::t],
191         vtables: Option<typeck::vtable_res>)
192      -> Callee {
193     Callee {bcx: bcx,
194             data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ref_id,
195                                                type_params, vtables))}
196 }
197
198 fn resolve_default_method_vtables(bcx: @mut Block,
199                                   impl_id: ast::def_id,
200                                   method: &ty::Method,
201                                   substs: &ty::substs,
202                                   impl_vtables: Option<typeck::vtable_res>)
203                           -> (typeck::vtable_res, typeck::vtable_param_res) {
204
205     // Get the vtables that the impl implements the trait at
206     let impl_res = ty::lookup_impl_vtables(bcx.tcx(), impl_id);
207
208     // Build up a param_substs that we are going to resolve the
209     // trait_vtables under.
210     let param_substs = Some(@param_substs {
211         tys: substs.tps.clone(),
212         self_ty: substs.self_ty,
213         vtables: impl_vtables,
214         self_vtables: None
215     });
216
217     let trait_vtables_fixed = resolve_vtables_under_param_substs(
218         bcx.tcx(), param_substs, impl_res.trait_vtables);
219
220     // Now we pull any vtables for parameters on the actual method.
221     let num_method_vtables = method.generics.type_param_defs.len();
222     let method_vtables = match impl_vtables {
223         Some(vtables) => {
224             let num_impl_type_parameters =
225                 vtables.len() - num_method_vtables;
226             vtables.tailn(num_impl_type_parameters).to_owned()
227         },
228         None => vec::from_elem(num_method_vtables, @~[])
229     };
230
231     let param_vtables = @(*trait_vtables_fixed + method_vtables);
232
233     let self_vtables = resolve_param_vtables_under_param_substs(
234         bcx.tcx(), param_substs, impl_res.self_vtables);
235
236     (param_vtables, self_vtables)
237 }
238
239
240 pub fn trans_fn_ref_with_vtables(
241         bcx: @mut Block,       //
242         def_id: ast::def_id,   // def id of fn
243         ref_id: ast::NodeId,  // node id of use of fn; may be zero if N/A
244         type_params: &[ty::t], // values for fn's ty params
245         vtables: Option<typeck::vtable_res>) // vtables for the call
246      -> FnData {
247     /*!
248      * Translates a reference to a fn/method item, monomorphizing and
249      * inlining as it goes.
250      *
251      * # Parameters
252      *
253      * - `bcx`: the current block where the reference to the fn occurs
254      * - `def_id`: def id of the fn or method item being referenced
255      * - `ref_id`: node id of the reference to the fn/method, if applicable.
256      *   This parameter may be zero; but, if so, the resulting value may not
257      *   have the right type, so it must be cast before being used.
258      * - `type_params`: values for each of the fn/method's type parameters
259      * - `vtables`: values for each bound on each of the type parameters
260      */
261
262     let _icx = push_ctxt("trans_fn_ref_with_vtables");
263     let ccx = bcx.ccx();
264     let tcx = ccx.tcx;
265
266     debug!("trans_fn_ref_with_vtables(bcx=%s, def_id=%s, ref_id=%?, \
267             type_params=%s, vtables=%s)",
268            bcx.to_str(),
269            def_id.repr(bcx.tcx()),
270            ref_id,
271            type_params.repr(bcx.tcx()),
272            vtables.repr(bcx.tcx()));
273
274     assert!(type_params.iter().all(|t| !ty::type_needs_infer(*t)));
275
276     // Polytype of the function item (may have type params)
277     let fn_tpt = ty::lookup_item_type(tcx, def_id);
278
279     let substs = ty::substs { regions: ty::ErasedRegions,
280                               self_ty: None,
281                               tps: /*bad*/ type_params.to_owned() };
282
283     // We need to do a bunch of special handling for default methods.
284     // We need to modify the def_id and our substs in order to monomorphize
285     // the function.
286     let (is_default, def_id, substs, self_vtables, vtables) =
287         match ty::provided_source(tcx, def_id) {
288         None => (false, def_id, substs, None, vtables),
289         Some(source_id) => {
290             // There are two relevant substitutions when compiling
291             // default methods. First, there is the substitution for
292             // the type parameters of the impl we are using and the
293             // method we are calling. This substitution is the substs
294             // argument we already have.
295             // In order to compile a default method, though, we need
296             // to consider another substitution: the substitution for
297             // the type parameters on trait; the impl we are using
298             // implements the trait at some particular type
299             // parameters, and we need to substitute for those first.
300             // So, what we need to do is find this substitution and
301             // compose it with the one we already have.
302
303             let impl_id = ty::method(tcx, def_id).container_id;
304             let method = ty::method(tcx, source_id);
305             let trait_ref = ty::impl_trait_ref(tcx, impl_id)
306                 .expect("could not find trait_ref for impl with \
307                          default methods");
308
309             // Compute the first substitution
310             let first_subst = make_substs_for_receiver_types(
311                 tcx, impl_id, trait_ref, method);
312
313             // And compose them
314             let new_substs = first_subst.subst(tcx, &substs);
315
316
317             let (param_vtables, self_vtables) =
318                 resolve_default_method_vtables(bcx, impl_id,
319                                                method, &substs, vtables);
320
321             debug!("trans_fn_with_vtables - default method: \
322                     substs = %s, trait_subst = %s, \
323                     first_subst = %s, new_subst = %s, \
324                     vtables = %s, \
325                     self_vtable = %s, param_vtables = %s",
326                    substs.repr(tcx), trait_ref.substs.repr(tcx),
327                    first_subst.repr(tcx), new_substs.repr(tcx),
328                    vtables.repr(tcx),
329                    self_vtables.repr(tcx), param_vtables.repr(tcx));
330
331             (true, source_id,
332              new_substs, Some(self_vtables), Some(param_vtables))
333         }
334     };
335
336     // Check whether this fn has an inlined copy and, if so, redirect
337     // def_id to the local id of the inlined copy.
338     let def_id = {
339         if def_id.crate != ast::LOCAL_CRATE {
340             inline::maybe_instantiate_inline(ccx, def_id)
341         } else {
342             def_id
343         }
344     };
345
346     // We must monomorphise if the fn has type parameters, is a rust
347     // intrinsic, or is a default method.  In particular, if we see an
348     // intrinsic that is inlined from a different crate, we want to reemit the
349     // intrinsic instead of trying to call it in the other crate.
350     let must_monomorphise;
351     if type_params.len() > 0 || is_default {
352         must_monomorphise = true;
353     } else if def_id.crate == ast::LOCAL_CRATE {
354         let map_node = session::expect(
355             ccx.sess,
356             ccx.tcx.items.find(&def_id.node),
357             || fmt!("local item should be in ast map"));
358
359         match *map_node {
360             ast_map::node_foreign_item(_, abis, _, _) => {
361                 must_monomorphise = abis.is_intrinsic()
362             }
363             _ => {
364                 must_monomorphise = false;
365             }
366         }
367     } else {
368         must_monomorphise = false;
369     }
370
371     // Create a monomorphic verison of generic functions
372     if must_monomorphise {
373         // Should be either intra-crate or inlined.
374         assert_eq!(def_id.crate, ast::LOCAL_CRATE);
375
376         let (val, must_cast) =
377             monomorphize::monomorphic_fn(ccx, def_id, &substs,
378                                          vtables, self_vtables,
379                                          Some(ref_id));
380         let mut val = val;
381         if must_cast && ref_id != 0 {
382             // Monotype of the REFERENCE to the function (type params
383             // are subst'd)
384             let ref_ty = common::node_id_type(bcx, ref_id);
385
386             val = PointerCast(
387                 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
388         }
389         return FnData {llfn: val};
390     }
391
392     // Find the actual function pointer.
393     let mut val = {
394         if def_id.crate == ast::LOCAL_CRATE {
395             // Internal reference.
396             get_item_val(ccx, def_id.node)
397         } else {
398             // External reference.
399             trans_external_path(ccx, def_id, fn_tpt.ty)
400         }
401     };
402
403     // This is subtle and surprising, but sometimes we have to bitcast
404     // the resulting fn pointer.  The reason has to do with external
405     // functions.  If you have two crates that both bind the same C
406     // library, they may not use precisely the same types: for
407     // example, they will probably each declare their own structs,
408     // which are distinct types from LLVM's point of view (nominal
409     // types).
410     //
411     // Now, if those two crates are linked into an application, and
412     // they contain inlined code, you can wind up with a situation
413     // where both of those functions wind up being loaded into this
414     // application simultaneously. In that case, the same function
415     // (from LLVM's point of view) requires two types. But of course
416     // LLVM won't allow one function to have two types.
417     //
418     // What we currently do, therefore, is declare the function with
419     // one of the two types (whichever happens to come first) and then
420     // bitcast as needed when the function is referenced to make sure
421     // it has the type we expect.
422     //
423     // This can occur on either a crate-local or crate-external
424     // reference. It also occurs when testing libcore and in some
425     // other weird situations. Annoying.
426     let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
427     let llptrty = llty.ptr_to();
428     if val_ty(val) != llptrty {
429         val = BitCast(bcx, val, llptrty);
430     }
431
432     return FnData {llfn: val};
433 }
434
435 // ______________________________________________________________________
436 // Translating calls
437
438 pub fn trans_call(in_cx: @mut Block,
439                   call_ex: @ast::expr,
440                   f: @ast::expr,
441                   args: CallArgs,
442                   id: ast::NodeId,
443                   dest: expr::Dest)
444                   -> @mut Block {
445     let _icx = push_ctxt("trans_call");
446     trans_call_inner(in_cx,
447                      call_ex.info(),
448                      expr_ty(in_cx, f),
449                      node_id_type(in_cx, id),
450                      |cx| trans(cx, f),
451                      args,
452                      Some(dest),
453                      DontAutorefArg).bcx
454 }
455
456 pub fn trans_method_call(in_cx: @mut Block,
457                          call_ex: @ast::expr,
458                          callee_id: ast::NodeId,
459                          rcvr: @ast::expr,
460                          args: CallArgs,
461                          dest: expr::Dest)
462                          -> @mut Block {
463     let _icx = push_ctxt("trans_method_call");
464     debug!("trans_method_call(call_ex=%s, rcvr=%s)",
465            call_ex.repr(in_cx.tcx()),
466            rcvr.repr(in_cx.tcx()));
467     trans_call_inner(
468         in_cx,
469         call_ex.info(),
470         node_id_type(in_cx, callee_id),
471         expr_ty(in_cx, call_ex),
472         |cx| {
473             match cx.ccx().maps.method_map.find_copy(&call_ex.id) {
474                 Some(origin) => {
475                     debug!("origin for %s: %s",
476                            call_ex.repr(in_cx.tcx()),
477                            origin.repr(in_cx.tcx()));
478
479                     meth::trans_method_callee(cx,
480                                               callee_id,
481                                               rcvr,
482                                               origin)
483                 }
484                 None => {
485                     cx.tcx().sess.span_bug(call_ex.span, "method call expr wasn't in method map")
486                 }
487             }
488         },
489         args,
490         Some(dest),
491         DontAutorefArg).bcx
492 }
493
494 pub fn trans_lang_call(bcx: @mut Block,
495                        did: ast::def_id,
496                        args: &[ValueRef],
497                        dest: Option<expr::Dest>)
498     -> Result {
499     let fty = if did.crate == ast::LOCAL_CRATE {
500         ty::node_id_to_type(bcx.ccx().tcx, did.node)
501     } else {
502         csearch::get_type(bcx.ccx().tcx, did).ty
503     };
504     let rty = ty::ty_fn_ret(fty);
505     callee::trans_call_inner(bcx,
506                              None,
507                              fty,
508                              rty,
509                              |bcx| {
510                                 trans_fn_ref_with_vtables_to_callee(bcx,
511                                                                     did,
512                                                                     0,
513                                                                     [],
514                                                                     None)
515                              },
516                              ArgVals(args),
517                              dest,
518                              DontAutorefArg)
519 }
520
521 pub fn trans_lang_call_with_type_params(bcx: @mut Block,
522                                         did: ast::def_id,
523                                         args: &[ValueRef],
524                                         type_params: &[ty::t],
525                                         dest: expr::Dest)
526     -> @mut Block {
527     let fty;
528     if did.crate == ast::LOCAL_CRATE {
529         fty = ty::node_id_to_type(bcx.tcx(), did.node);
530     } else {
531         fty = csearch::get_type(bcx.tcx(), did).ty;
532     }
533
534     let rty = ty::ty_fn_ret(fty);
535     return callee::trans_call_inner(
536         bcx, None, fty, rty,
537         |bcx| {
538             let callee =
539                 trans_fn_ref_with_vtables_to_callee(bcx, did, 0,
540                                                     type_params,
541                                                     None);
542
543             let new_llval;
544             match callee.data {
545                 Fn(fn_data) => {
546                     let substituted = ty::subst_tps(callee.bcx.tcx(),
547                                                     type_params,
548                                                     None,
549                                                     fty);
550                     let llfnty = type_of::type_of(callee.bcx.ccx(),
551                                                       substituted);
552                     new_llval = PointerCast(callee.bcx, fn_data.llfn, llfnty);
553                 }
554                 _ => fail!()
555             }
556             Callee { bcx: callee.bcx, data: Fn(FnData { llfn: new_llval }) }
557         },
558         ArgVals(args), Some(dest), DontAutorefArg).bcx;
559 }
560
561
562 struct CalleeTranslationVisitor;
563
564 impl Visitor<@mut bool> for CalleeTranslationVisitor {
565
566     fn visit_item(&mut self, _:@ast::item, _:@mut bool) { }
567
568     fn visit_expr(&mut self, e:@ast::expr, cx:@mut bool) {
569
570             if !*cx {
571                 match e.node {
572                   ast::expr_ret(_) => *cx = true,
573                   _ => visit::walk_expr(self, e, cx),
574                 }
575             }
576     }
577
578 }
579
580 pub fn body_contains_ret(body: &ast::Block) -> bool {
581     let cx = @mut false;
582     let mut v = CalleeTranslationVisitor;
583     visit::walk_block(&mut v, body, cx);
584     *cx
585 }
586
587 pub fn trans_call_inner(in_cx: @mut Block,
588                         call_info: Option<NodeInfo>,
589                         callee_ty: ty::t,
590                         ret_ty: ty::t,
591                         get_callee: &fn(@mut Block) -> Callee,
592                         args: CallArgs,
593                         dest: Option<expr::Dest>,
594                         autoref_arg: AutorefArg)
595                         -> Result {
596     /*!
597      * This behemoth of a function translates function calls.
598      * Unfortunately, in order to generate more efficient LLVM
599      * output at -O0, it has quite a complex signature (refactoring
600      * this into two functions seems like a good idea).
601      *
602      * In particular, for lang items, it is invoked with a dest of
603      * None, and
604      */
605
606
607     do base::with_scope_result(in_cx, call_info, "call") |cx| {
608         let callee = get_callee(cx);
609         let mut bcx = callee.bcx;
610         let ccx = cx.ccx();
611
612         let (llfn, llenv) = unsafe {
613             match callee.data {
614                 Fn(d) => {
615                     (d.llfn, llvm::LLVMGetUndef(Type::opaque_box(ccx).ptr_to().to_ref()))
616                 }
617                 Method(d) => {
618                     // Weird but true: we pass self in the *environment* slot!
619                     (d.llfn, d.llself)
620                 }
621                 Closure(d) => {
622                     // Closures are represented as (llfn, llclosure) pair:
623                     // load the requisite values out.
624                     let pair = d.to_ref_llval(bcx);
625                     let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
626                     let llfn = Load(bcx, llfn);
627                     let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
628                     let llenv = Load(bcx, llenv);
629                     (llfn, llenv)
630                 }
631             }
632         };
633
634         let abi = match ty::get(callee_ty).sty {
635             ty::ty_bare_fn(ref f) => f.abis,
636             _ => AbiSet::Rust()
637         };
638         let is_rust_fn =
639             abi.is_rust() ||
640             abi.is_intrinsic();
641
642         // Generate a location to store the result. If the user does
643         // not care about the result, just make a stack slot.
644         let opt_llretslot = match dest {
645             None => {
646                 assert!(!type_of::return_uses_outptr(in_cx.tcx(), ret_ty));
647                 None
648             }
649             Some(expr::SaveIn(dst)) => Some(dst),
650             Some(expr::Ignore) => {
651                 if !ty::type_is_voidish(ret_ty) {
652                     Some(alloc_ty(bcx, ret_ty, "__llret"))
653                 } else {
654                     unsafe {
655                         Some(llvm::LLVMGetUndef(Type::nil().ptr_to().to_ref()))
656                     }
657                 }
658             }
659         };
660
661         let mut llresult = unsafe {
662             llvm::LLVMGetUndef(Type::nil().ptr_to().to_ref())
663         };
664
665         // The code below invokes the function, using either the Rust
666         // conventions (if it is a rust fn) or the native conventions
667         // (otherwise).  The important part is that, when all is sad
668         // and done, either the return value of the function will have been
669         // written in opt_llretslot (if it is Some) or `llresult` will be
670         // set appropriately (otherwise).
671         if is_rust_fn {
672             let mut llargs = ~[];
673
674             // Push the out-pointer if we use an out-pointer for this
675             // return type, otherwise push "undef".
676             if type_of::return_uses_outptr(in_cx.tcx(), ret_ty) {
677                 llargs.push(opt_llretslot.unwrap());
678             }
679
680             // Push the environment.
681             llargs.push(llenv);
682
683             // Push the arguments.
684             bcx = trans_args(bcx, args, callee_ty,
685                              autoref_arg, &mut llargs);
686
687             // Now that the arguments have finished evaluating, we
688             // need to revoke the cleanup for the self argument
689             match callee.data {
690                 Method(d) => {
691                     for &v in d.temp_cleanup.iter() {
692                         revoke_clean(bcx, v);
693                     }
694                 }
695                 _ => {}
696             }
697
698             // Invoke the actual rust fn and update bcx/llresult.
699             let (llret, b) = base::invoke(bcx, llfn, llargs);
700             bcx = b;
701             llresult = llret;
702
703             // If the Rust convention for this type is return via
704             // the return value, copy it into llretslot.
705             match opt_llretslot {
706                 Some(llretslot) => {
707                     if !type_of::return_uses_outptr(bcx.tcx(), ret_ty) &&
708                         !ty::type_is_voidish(ret_ty)
709                     {
710                         Store(bcx, llret, llretslot);
711                     }
712                 }
713                 None => {}
714             }
715         } else {
716             // Lang items are the only case where dest is None, and
717             // they are always Rust fns.
718             assert!(dest.is_some());
719
720             let mut llargs = ~[];
721             bcx = trans_args(bcx, args, callee_ty,
722                              autoref_arg, &mut llargs);
723             bcx = foreign::trans_native_call(bcx, callee_ty,
724                                              llfn, opt_llretslot.unwrap(), llargs);
725         }
726
727         // If the caller doesn't care about the result of this fn call,
728         // drop the temporary slot we made.
729         match dest {
730             None => {
731                 assert!(!type_of::return_uses_outptr(bcx.tcx(), ret_ty));
732             }
733             Some(expr::Ignore) => {
734                 // drop the value if it is not being saved.
735                 bcx = glue::drop_ty(bcx, opt_llretslot.unwrap(), ret_ty);
736             }
737             Some(expr::SaveIn(_)) => { }
738         }
739
740         if ty::type_is_bot(ret_ty) {
741             Unreachable(bcx);
742         }
743
744         rslt(bcx, llresult)
745     }
746 }
747
748 pub enum CallArgs<'self> {
749     ArgExprs(&'self [@ast::expr]),
750     ArgVals(&'self [ValueRef])
751 }
752
753 pub fn trans_args(cx: @mut Block,
754                   args: CallArgs,
755                   fn_ty: ty::t,
756                   autoref_arg: AutorefArg,
757                   llargs: &mut ~[ValueRef]) -> @mut Block
758 {
759     let _icx = push_ctxt("trans_args");
760     let mut temp_cleanups = ~[];
761     let arg_tys = ty::ty_fn_args(fn_ty);
762
763     let mut bcx = cx;
764
765     // First we figure out the caller's view of the types of the arguments.
766     // This will be needed if this is a generic call, because the callee has
767     // to cast her view of the arguments to the caller's view.
768     match args {
769       ArgExprs(arg_exprs) => {
770         for (i, arg_expr) in arg_exprs.iter().enumerate() {
771             let arg_val = unpack_result!(bcx, {
772                 trans_arg_expr(bcx,
773                                arg_tys[i],
774                                ty::ByCopy,
775                                *arg_expr,
776                                &mut temp_cleanups,
777                                autoref_arg)
778             });
779             llargs.push(arg_val);
780         }
781       }
782       ArgVals(vs) => {
783         llargs.push_all(vs);
784       }
785     }
786
787     // now that all arguments have been successfully built, we can revoke any
788     // temporary cleanups, as they are only needed if argument construction
789     // should fail (for example, cleanup of copy mode args).
790     for c in temp_cleanups.iter() {
791         revoke_clean(bcx, *c)
792     }
793
794     bcx
795 }
796
797 pub enum AutorefArg {
798     DontAutorefArg,
799     DoAutorefArg
800 }
801
802 // temp_cleanups: cleanups that should run only if failure occurs before the
803 // call takes place:
804 pub fn trans_arg_expr(bcx: @mut Block,
805                       formal_arg_ty: ty::t,
806                       self_mode: ty::SelfMode,
807                       arg_expr: @ast::expr,
808                       temp_cleanups: &mut ~[ValueRef],
809                       autoref_arg: AutorefArg) -> Result {
810     let _icx = push_ctxt("trans_arg_expr");
811     let ccx = bcx.ccx();
812
813     debug!("trans_arg_expr(formal_arg_ty=(%s), self_mode=%?, arg_expr=%s)",
814            formal_arg_ty.repr(bcx.tcx()),
815            self_mode,
816            arg_expr.repr(bcx.tcx()));
817
818     // translate the arg expr to a datum
819     let arg_datumblock = expr::trans_to_datum(bcx, arg_expr);
820     let arg_datum = arg_datumblock.datum;
821     let bcx = arg_datumblock.bcx;
822
823     debug!("   arg datum: %s", arg_datum.to_str(bcx.ccx()));
824
825     let mut val;
826     if ty::type_is_bot(arg_datum.ty) {
827         // For values of type _|_, we generate an
828         // "undef" value, as such a value should never
829         // be inspected. It's important for the value
830         // to have type lldestty (the callee's expected type).
831         let llformal_arg_ty = type_of::type_of(ccx, formal_arg_ty);
832         unsafe {
833             val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
834         }
835     } else {
836         // FIXME(#3548) use the adjustments table
837         match autoref_arg {
838             DoAutorefArg => {
839                 val = arg_datum.to_ref_llval(bcx);
840             }
841             DontAutorefArg => {
842                 let need_scratch = ty::type_needs_drop(bcx.tcx(), arg_datum.ty) ||
843                     (bcx.expr_is_lval(arg_expr) &&
844                      arg_datum.appropriate_mode(bcx.tcx()).is_by_ref());
845
846                 let arg_datum = if need_scratch {
847                     let scratch = scratch_datum(bcx, arg_datum.ty, "__self", false);
848                     arg_datum.store_to_datum(bcx, INIT, scratch);
849
850                     // Technically, ownership of val passes to the callee.
851                     // However, we must cleanup should we fail before the
852                     // callee is actually invoked.
853                     scratch.add_clean(bcx);
854                     temp_cleanups.push(scratch.val);
855
856                     scratch
857                 } else {
858                     arg_datum
859                 };
860
861                 val = match self_mode {
862                     ty::ByRef => {
863                         debug!("by ref arg with type %s", bcx.ty_to_str(arg_datum.ty));
864                         arg_datum.to_ref_llval(bcx)
865                     }
866                     ty::ByCopy => {
867                         debug!("by copy arg with type %s", bcx.ty_to_str(arg_datum.ty));
868                         arg_datum.to_appropriate_llval(bcx)
869                     }
870                 }
871             }
872         }
873
874         if formal_arg_ty != arg_datum.ty {
875             // this could happen due to e.g. subtyping
876             let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
877             debug!("casting actual type (%s) to match formal (%s)",
878                    bcx.val_to_str(val), bcx.llty_str(llformal_arg_ty));
879             val = PointerCast(bcx, val, llformal_arg_ty);
880         }
881     }
882
883     debug!("--- trans_arg_expr passing %s", bcx.val_to_str(val));
884     return rslt(bcx, val);
885 }