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