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